BufferedReader readLine()问题:检测文件结束和空返回行

我希望我的程序在最后一行文本末尾找到文件结尾(EOF)时执行某些操作,而当EOF位于最后一行文本后的空行时则执行其他操作。 不幸的是,BufferedReader似乎认为两种情况都是平等的。

例如,这是我的代码,用于读取文件末尾的行:

FileReader fr = new FileReader("file.txt"); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine()) != null) { if (line.equals("")) { System.out.println("Found an empty line at end of file."); } } 

如果file.txt包含此内容,则不会打印:

 line of text 1 another line 2//cursor 

这也不会打印:

 line of text 1 another line 2 //cursor 

但是,这将:

 line of text 1 another line 2 //cursor 

我可以使用哪些读者来区分前两种情况?

您将不得不使用read而不是readLine并自己处理行尾检测。 readLine认为\n\r和EOF都是行终止符,并且不包含它返回的终结符,因此您无法根据返回的字符串进行区分。

您可以使用BufferedReader.read(char[] cbuf, int off, int len)方法。 当到达文件结尾时,返回值-1 ,您可以检查最后一个缓冲区读取是否以行分隔符结束。

不可否认,代码会更复杂,因为它必须从read char[]缓冲区管理行的构造。

 public ArrayList readFile(String inputFilename) throws IOException { BufferedReader br = new BufferedReader(new FileReader(inputFilename)); ArrayList lines = new ArrayList<>(); String currentLine = ""; int currentCharacter = br.read(); int lastCharacter = -1; // Loop through each character read. while (currentCharacter != -1) { // Skip carriage returns. if (currentCharacter != '\r') { // Add the currentLine at each line feed and then reset currentLine. if (currentCharacter == '\n') { lines.add(currentLine); currentLine = ""; } else { // Add each non-line-separating character to the currentLine. currentLine += (char) currentCharacter; } } // Keep track of the last read character and continue reading the next // character. lastCharacter = currentCharacter; currentCharacter = br.read(); } br.close(); // If the currentLine is not empty, add it to the end of the ArrayList. if (!currentLine.isEmpty()) { lines.add(currentLine); } // If the last read character was a line feed, add another String to the end // of the ArrayList. if (lastCharacter == '\n') { lines.add(""); } return lines; } 

为什么不用

 if (line.length()==0) { System.out.println("Found an empty line."); } 

注意:这将检测文件中任何位置的空行,而不仅仅是EOF。