我想製作一個程序,讀取TextField
中的用戶輸入,並將其保存到保存到文件的ArrayList
中。然後,按鈕將允許用戶通過輸入他們正在尋找的動物的名稱來從ArrayList
中刪除對象(包含從中導入動物的名稱,ID和國家)。這是按下刪除按鈕時調用的方法的代碼。我得到FileNotFoundException
,我不明白爲什麼。你能幫我嗎?從ArrayList中打印對象,無法找到文件
public void DeleteLine(String fileName,String strSearched){
try {
ObjectInputStream os = new ObjectInputStream(new FileInputStream(fileName));
ObjectInputStream osTMP = new ObjectInputStream(new FileInputStream("ZooTMP.txt"));
animal = (ArrayList<ANIMAL>) os.readObject();
System.out.println("Original contents of animal: ");
Iterator itr = animal.iterator();
while(itr.hasNext()) {
Object ANIMAL = itr.next();
if (ANIMAL.contains(strSearched)) {
itr.remove();
}
}
System.out.println();
os.close();
osTMP.close();
} catch (FileNotFoundException ex) {
System.out.println("Can't find the file Zoo.txt");
} catch (IOException ex) {
System.out.println("The file Zoo.txt has already been closed");
} catch (ClassNotFoundException ex) {
System.out.printf("Class is missing: %s\n",ex);
}
}
這是接口的動物:
package GUI_Try;
import java.io.*;
class ANIMAL implements Serializable {
String name, ID, country;
public ANIMAL(String name, String ID, String country){
this.name = name;
this.ID = ID;
this.country = country;
}
}
確保'fileName'指向一個文件,該文件位於您啓動程序的任何位置的工作目錄中。 –
FileNotFoundException中的消息是什麼?文件名是絕對路徑,還是在工作目錄中?它存在嗎?考慮添加一些打印或記錄文件名的調試代碼,並測試文件是否存在 - 'boolean isExtant = new File(fileName).exists()。' –
看起來像我從文件加載數據時,數據是正確閱讀並加載所有內容。但是,我無法在我選擇的目錄中找到該文件。我無法在其他任何地方找到它。 FileNotFoundException是由未使用的'osTMP'造成的。但是,我仍然想知道這個文件在哪裏。 –