[英]Java open file error: can't find the specified path
I try to open a .txt file (agenda.txt) from the src/resources folder, read objects from it and add them to an ArrayList, but I get this error: "The system can not find the specified path.". 我尝试从src / resources文件夹中打开一个.txt文件(agenda.txt),从中读取对象并将它们添加到ArrayList,但是出现此错误:“系统找不到指定的路径。”。 This is the code I use:
这是我使用的代码:
public void open(File f) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
Object o;
try {
while ((o = ois.readObject()) != null) {
model.adauga((Abonat) o);
}
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Clasa...!",
JOptionPane.ERROR_MESSAGE);
return;
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(
this,
ex.getMessage(),
"Eroare deschidere fisier!",
JOptionPane.ERROR_MESSAGE);
return;
} finally {
try {
ois.close();
} catch (IOException ex) {
Logger.getLogger(CarteDeTelefonGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And in the class constructor: 并在类构造函数中:
private String path ="resources/agenda.txt";
File f=new File(path);
open(f);
What is wrong in the code? 代码有什么问题?
the file should be located outside src , something like baseproject/resources . 该文件应位于src外部,类似于baseproject / resources 。 Thats because your path is the project base not your sources directory.
那是因为您的路径是项目基础而不是源目录。 Or you can change the code to
或者您可以将代码更改为
private String path ="src/resources/agenda.txt";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.