我想制作一个程序,读取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'造成的。但是,我仍然想知道这个文件在哪里。 –