[英]FileReader not reading entire text file
我希望我的代码读取一个 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
。
对于不想一次加载到 memory 的大文件,可以使用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...");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.