[英]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());
如果您嘗試將文件附加到基於servlet的Web應用程序中,則應嘗試如下操作:
String file =request.getSession().getServletContext().getRealPath("/")+"\\file.name";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.