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());

}

或者。。扫描仪可以将文件参数作为输入。。。


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...");

最简单的方法是使用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);
});
}

最新更新