FileReader 不读取整个文本文件

问题描述

我希望我的代码读取一个 txt 文件并打印出每一行,但几乎一半的行似乎是随机跳过的。如何确保读取整个文件

        BufferedInputStream readIt = new BufferedInputStream(new FileInputStream(pBase));
        //pBase is txt File object
        Scanner actualRead = new Scanner(readIt);

    
        while(actualRead.hasNextLine()){
            System.out.println("Line is : " + actualRead.nextLine());
            
        }

解决方法

最简单的方法是使用 nio 实用程序方法之一,例如 readAllLines

对于不想一次性全部加载到内存中的大文件,可以像这样使用 lines 方法:

import java.nio.file.Files;
import java.nio.file.Path;
...
try (var lines = Files.lines(Paths.get(pBase))) {
  lines.forEach(l -> {
    System.out.println(l);
  });
}
,

或者..scanner 可以将文件参数作为输入...


Scanner actualRead = new Scanner(pBase); //directly pass the file as argument...
//Although this threatens to throw an IOException..catch  it in try-catch or add to throws...
try {
  Scanner actualRead = new Scanner(pBase);
  while (actualRead.hasNextLine()) {
    System.out.println("Line is : " + actualRead.nextLine());
}
catch (IOException e) {
  System.out.println("err...");