簡體   English   中英

BufferedReader不會讀取文本文件中的所有行

[英]BufferedReader does not read all the lines in text file

我有一個功能。

public ArrayList<String> readRules(String src) {
    try (BufferedReader br = new BufferedReader(new FileReader(src))) {
        String sCurrentLine;
        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
            lines.add(sCurrentLine);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return lines;
}

我的文件有26.400行,但是此功能僅在文件末尾讀取3400行。 如何讀取文件中的所有行。 謝謝!

為什么不使用實用程序方法Files.readAllLines() (從Java 7開始可用)?

此方法確保在讀取所有字節或引發IOException(或另一個運行時異常)后關閉文件。

使用指定的字符集將文件中的字節解碼為字符。

public ArrayList<String> readRules(String src) {
    return Files.readAllLines(src, Charset.defaultCharset());
}
  while ((sCurrentLine = br.readLine()) != null)

您可能有一個空行或被視為null

嘗試

while(br.hasNextLine())
{
    String current = br.nextLine();
}

編輯:或者,在文本文件中,當一行太長時,編輯器會自動將一行換成多行。 如果不使用return key ,則BufferedReader會將其視為一行。

Notepad ++是防止將單行與多行混淆的好工具。 它針對返回鍵的使用對行進行編號。 也許您可以將輸入文件復制/粘貼到Notepad++然后檢查行號是否匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM