簡體   English   中英

BufferedReader.readLine() 將所有行返回為 null

[英]BufferedReader.readLine() returning all lines as null

我有一些非常簡單的代碼來准備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();
    }

}

}

通過使用lines()方法,您基本上將緩沖讀取器 position 移動到文件末尾。 就像您已經閱讀了這些行一樣。

嘗試使用它來遍歷所有行:

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

使用br.lines()br.readLine()來使用輸入,但不能同時使用兩者。 此版本僅使用 stream 到 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"));

暫無
暫無

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

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