filenotfoundexception 和文件存在
filenotfoundexception and file exists
不是我第一次使用java中的文件,但这是我第一次使用FileInputStream
。
我在 resources/backup.txt 中有一个 TXT
然后在我的代码中,当我将文件放入 FileInputStream
构造函数时,它会抛出一个 FileNotFoundException
.
这是代码:
public void loadList() {
try {
ArrayList<Partido> myList = Pronosticos.getInstance().getMyList();
myList.clear();
File file = new File("resources/backup.txt");
// create an ObjectInputStream for the file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
// read and print an object and cast it as ArrayList<Partido>
if (file.length() != 0){
myList .addAll((ArrayList<Partido>) ois.readObject());
ois.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
我不应该从我的 PC 中放置路径,因为我需要它在另一台 PC 上工作。
尝试像这样加载文件:
URL url = getClass().getResource("backup.txt");
File file = new File(url.getPath());
并将文件对象传递给FileInputStream
这应该有效。我使用相同的项目设置对此进行了测试:
//note the beginning forward slash
URL url = getClass().getResource("/backup.txt");
File file = new File(url.getPath());
不是我第一次使用java中的文件,但这是我第一次使用FileInputStream
。
我在 resources/backup.txt 中有一个 TXT
然后在我的代码中,当我将文件放入 FileInputStream
构造函数时,它会抛出一个 FileNotFoundException
.
这是代码:
public void loadList() {
try {
ArrayList<Partido> myList = Pronosticos.getInstance().getMyList();
myList.clear();
File file = new File("resources/backup.txt");
// create an ObjectInputStream for the file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
// read and print an object and cast it as ArrayList<Partido>
if (file.length() != 0){
myList .addAll((ArrayList<Partido>) ois.readObject());
ois.close();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
我不应该从我的 PC 中放置路径,因为我需要它在另一台 PC 上工作。
尝试像这样加载文件:
URL url = getClass().getResource("backup.txt");
File file = new File(url.getPath());
并将文件对象传递给FileInputStream
这应该有效。我使用相同的项目设置对此进行了测试:
//note the beginning forward slash
URL url = getClass().getResource("/backup.txt");
File file = new File(url.getPath());