我正在尝试读取文件,但它无法正常工作。我在这里看了很多例子,我使用的方法是从别人的问题的答案中借用的。我知道您可以使用 bufferedreader,但我想坚持使用我所知道的以及现在在类里面学习的内容。当我运行此代码时,我只得到一个空行,但该文件包含 4 行信息。
import java.io.*;
import java.util.Scanner;
import java.lang.StringBuilder;
import java.io.File;
import java.io.FileInputStream;
public class fileWriting{
public static void main(String[] args) throws IOException{
//Set everything up to read & write files
//Create new file(s)
File accInfo = new File("accountInfo.txt");
//Create FileWriter
Scanner in = new Scanner(new FileReader("accountInfo.txt"));
String fileString = "";
//read from text file to update current information into program
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
fileString = sb.toString();
System.out.println(fileString);
}
}
我的文件包含以下文本:
姓名:霍华德
检查:0
节省:0
信用:0
最佳答案
与使用 Scanner 相比,使用 BufferedReader 之类的优点之一是,如果读取因任何原因失败,您将收到异常。这是一件好事——您想知道程序何时以及为何失败,而不是猜测。
扫描仪不会引发异常。相反,您必须手动检查:
if (in.ioException() != null) {
throw in.ioException();
}
这样的检查可能属于程序末尾附近,在 while
循环之后。这不会让你的程序正常工作,但它应该告诉你出了什么问题,这样你就可以解决问题。
当然,您还应该验证 accountInfo.txt 中是否确实包含一些文本。
关于java - FileReader 在 Java 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087349/