这不是我第一次在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();
}
}
我不应该从我的电脑上放置Path,因为我需要它在另一台电脑上工作。
这应该工作。我用相同的项目设置测试了这个:
//note the beginning forward slash
URL url = getClass().getResource("/backup.txt");
File file = new File(url.getPath());
尝试像这样加载文件:
URL url = getClass().getResource("backup.txt");
File file = new File(url.getPath());
并将文件对象传递给FileInputStream
如果您尝试将文件附加到基于servlet的Web应用程序,您应该尝试这样的事情:
String file =request.getSession().getServletContext().getRealPath("/")+"\\file.name";