2012-03-29 22 views
4

私のプログラムは、テキストの最後の行の最後にファイルの終わり(EOF)を見つけたら何かをしたい。そのテキストの最後の行の後に空行にEOFがあります。残念ながら、BufferedReaderは両方のケースを等しいとみなしているようです。BufferedReader readLine()問題:ファイルの終わりと空の戻り行を検出する

例えば、これはファイルの最後にラインを読むために私のコードです:

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 

最初の2つのケースを区別するためにどのような読者を使用できますか?

答えて

3

BufferedReader.read(char[] cbuf, int off, int len)メソッドを使用できます。ファイルの終わりに達すると、戻り値-1、最後のバッファ読込みが行区切り記号で終了したかどうか確認できます。

確かに、コードは、読み取り済みのchar[]バッファからの行の構成を管理する必要があるため、より複雑になります。

4

readLineではなくreadを使用し、自分で行末の検出を処理する必要があります。 readLineは、\n\r、およびEOF allを行終端文字と見なし、終端文字を返しません。したがって、返された文字列に基づいて区別することはできません。

-1

なぜ

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

注意を使用していない:これはだけでなく、EOFで、どこでもファイルに空白行を検出します。

+1

実際には、行が空で何も含まれていない場合でも、行はnullを返します。 –

0
public ArrayList<String> readFile(String inputFilename) throws IOException { 
    BufferedReader br = new BufferedReader(new FileReader(inputFilename)); 

    ArrayList<String> 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; 
} 
関連する問題