如果您的文件将始终保留在同一位置,您可以使用上面的答案,但如果它放在不同的操作系统(例如 Unix)上,/ 字符将无法按预期工作。因此,我会使用
FileReader parseFile = new FileReader(new File("input.txt").toAbsolutePath());
此代码假定 input.txt 与您的应用程序位于同一目录中。如果不是,则不能使用它。
如果您打算使用它来解析学生成绩,我建议不要完全使用 FileReader 或 BufferedReader。 NIO 有一个readAllLines(URI); 函数,它返回一个List<String>:
List<String> lines = Files.readAllLines(new File("input.txt").toAbsoluteFile().toURI());
这段代码仍然会抛出一个IOException,但它很容易完成这项工作,而且我发现它更容易使用。
或者,您可以调试可能引发IOexception 的原因并使用File API 阻止它们。例如:
public static String debugConnectionsToFile(File file) {
if(!file.exists()){
return "file does not exist!";
}
else if(!file.isFile()){
return "File is not actually a file!";
}
else if(!file.canRead()){
return "File cannot be read!";
}
else{
try {
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
try {
br.readLine();
br.close(); //It is true that this statement could cause an error, but it has never happened to me before.
} catch (IOException e) {
return "File cannot be read by the reader!";
}
} catch (FileNotFoundException e) {
return "File cannot be found or accessed by the reader";
}
return "It works fine!";
}
}
您可以通过构造函数File(String filepath)获取File对象。
希望这能回答你的问题!