即使文件存在,我也无法摆脱FileNotFound错误。有任何想法吗? (有数百行代码,因此我将在错误周围粘贴大块,如果这是一个问题,我可以发布更多)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
可能您的Windows未显示文件扩展名; nameList.txt?否则,工作目录不在带有子目录src的项目目录中。
A FileReader
使用默认字符集,因此该文件不可移植。如果在其他平台上运行该应用程序,则在开发人员的平台上运行,则编码错误。最好使用UTF-8,完整Unicode。
然后阅读会删除行尾:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
您可以做:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource"/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
如果是存储在应用程序jar中的只读文件,则它是资源而不是磁盘文件。