【问题标题】:BufferedReader.readLine() returning all lines as nullBufferedReader.readLine() 将所有行返回为 null
【发布时间】:2020-12-03 10:29:40
【问题描述】:

我有一些非常简单的代码来准备 txt 文件的内容,逐行并将其放入 String[],但是缓冲的阅读器将所有行返回为“null” - 知道可能是什么原因吗? *我想使用缓冲阅读器而不是其他选项,因为这只是 java 培训练习的一部分,而且我主要想了解我犯的错误在哪里。谢谢!

public static void readFile (String path){
    File file = new File(path);
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        int lineCount = (int) br.lines().count();
        String[] passwords = new String[lineCount];

        for (int i=0; i<lineCount; i++){
            passwords[i] = br.readLine();;
            System.out.println(passwords[i]);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

【问题讨论】:

  • br.lines().count() 不是行数,而是缓冲区中的元素数; lines() 返回缓冲区,而不是列表

标签: java bufferedreader


【解决方案1】:

通过使用lines() 方法,您基本上可以将缓冲的阅读器位置移动到文件末尾。就像您已经阅读了这些行一样。

尝试使用它来遍历所有行:

while ((line = br.readLine()) != null) {  
  // Use the line variable here  
}

【讨论】:

    【解决方案2】:

    使用br.lines()br.readLine() 来使用输入,但不能同时使用两者。这个版本只使用到 String[] 的流来做同样的事情,并在 try with resources 块中关闭输入:

    public static String[] readFile(Path path) throws IOException {
        try (BufferedReader br = Files.newBufferedReader(path);
            Stream<String> stream = br.lines()) {
            return stream.peek(System.out::println)
                              .collect(Collectors.toList())
                              .toArray(String[]::new);
        }
    }
    
    String[] values = readFile(Path.of("somefile.txt"));
    

    【讨论】:

    • 好,谢谢!问题在于计数,我认为它只是返回行数而没有真正遍历文件。
    猜你喜欢
    • 2013-06-29
    • 2016-05-20
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多