Довольно сложно прочитать ваш код.Пожалуйста, отформатируйте его в следующий раз.
Я создал файл с именем random_file.txt.Его содержимое следующее:
Это строка 1 ...
А это строка 2
Это еще одна строка ...
И еще один
И еще один
Теперь мы можем делать с файлом все, что вам нужно.Мы можем посчитать строки, распечатать каждую из них или разобрать их.Поскольку вы точно не указали, что вы хотите анализировать, я написал пример метода, который просто считает конкретное слово в файле.Синтаксический анализ должен выполняться с использованием RegularExpressions (regex).Вот хорошая ссылка для этого: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileParser
{
private String filepath;
public FileParser(String inputFilePath)
{
this.filepath = inputFilePath;
}
/**
* Counts the number of lines.
*
* @return Number of lines.
*
* @throws FileNotFoundException If the file doesn't exist.
* @throws IOException When an IO error occures.
*/
public int countLines() throws FileNotFoundException, IOException
{
File file = new File(filepath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int counter = 0;
while (br.readLine() != null)
{
counter++;
}
return counter;
}
/**
* Splits the lines of the file and returns a list.
* Each element of the list represents one line.
* Note that the line seperator is excluded.
*
* @throws FileNotFoundException If the file doesn't exist.
* @throws IOException When an IO error occures.
*/
public List<String> splitLines1() throws FileNotFoundException, IOException
{
File file = new File(filepath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
ArrayList<String> outputList = new ArrayList<>();
while ((line = br.readLine()) != null)
{
outputList.add(line);
}
if (br != null) br.close();
return outputList;
}
/**
* Splits the lines of the file and returns a String.
* Same as before, but now we have the line seperators included.
*
* @throws FileNotFoundException If the file doesn't exist.
* @throws IOException When an IO error occures.
*/
public String splitLines2() throws FileNotFoundException, IOException
{
File file = new File(filepath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null)
{
// we append every line to the builder
// note that we get one line seperator more than
// necessary (the one in the end)
builder.append(line + System.lineSeparator());
}
if (br != null) br.close();
return builder.toString();
}
/**
* An example method for parsing. In this method we count the
* number of times a word occures in given file.
*
* @param word The word we are looking for.
*
* @return Count the word occurencies.
*
* @throws FileNotFoundException If the file doesn't exist.
* @throws IOException When an IO error occures.
*/
public int countOccurencies(String word)
throws FileNotFoundException, IOException
{
List<String> fileLines = splitLines1(); // get the list, where each element represents one line
int counter = 0;
for (String line : fileLines)
{
// we split each line into words by splitting
// at the spaces
String[] words = line.split(" ");
for (int i = 0; i < words.length; i++)
{
if (words[i].equals(word)) counter++;
}
}
return counter;
}
/**
* Testing the methods.
*/
public static void main(String[] args) throws Exception
{
// Location of my file is in the project folder
String filePath = System.getProperty("user.dir") + File.separator
+ "random_file.txt";
FileParser fp = new FileParser(filePath);
System.out.println("The file has " + fp.countLines() + " lines."
+ System.lineSeparator());
System.out.println("We print a list holding each line as an element:");
System.out.println(fp.splitLines1()
.toString() + System.lineSeparator());
System.out
.println("Now we print the file contents as a single string:");
System.out.println(fp.splitLines2());
System.out
.println("Now we count the occurencies of the word \"line\":");
System.out.println(fp.countOccurencies("line"));
}
}
Вот вывод консоли:
The file has 5 lines.
We print a list holding each line as an element:
[This is line 1 ..., And this is line number 2, This is another line ..., And one more, And another one]
Now we print the file contents as a single string:
This is line 1 ...
And this is line number 2
This is another line ...
And one more
And another one
Now we count the occurencies of the word "line":
3