我正在尝试将Doctor类的对象读写到文件中。我不断收到此“ ClassNotFoundException”,这使我无法编译代码。
我尝试在其他文件上使用相同的方法,但似乎效果很好。
我在 Vector existing_v =(Vector)aois.readObject();
行出现编译错误 package com.example.docapp;
import java.io.*;
import java.util.*;
public class Admin implements Serializable {
public void addDoctor(Doctor D) throws Exception {
String url = "com\\example\\docapp\\doctorslist.txt";
File f = new File(url);
FileOutputStream afos = new FileOutputStream(f);
ObjectOutputStream aoos = new ObjectOutputStream(afos);
if(!f.exists()) { // If file doesnt exist creating and insert a new vector
Vector<Doctor> v = new Vector<Doctor>();
v.add(D);
aoos.writeObject(v);
}
else { // Extract the existing vector and add the object to it
FileInputStream afis = new FileInputStream(f);
ObjectInputStream aois = new ObjectInputStream(afis);
Vector<Doctor> existing_v = (Vector<Doctor>)aois.readObject();
existing_v.add(D);
aoos.writeObject(existing_v);
aois.close();
afis.close();
}
System.out.println("\n\nSuccessfully added " + D.name);
aoos.close();
afos.close();
}
}
答案 0 :(得分:0)
Admin类实际上不需要可序列化。您需要使Doctor
类实现Serializable
。
此外,当初始化FileOutputStream
时,如果不存在,它将创建文件。之后,!f.exists()
将永远不会评估为true,并且会弄乱您读取该对象的尝试。
public void addDoctor(Doctor D) throws Exception {
String url = "com\\example\\docapp\\doctorslist.txt";
File f = new File(url);
FileOutputStream afos;
ObjectOutputStream aoos;
if (!f.exists()) { // If file doesnt exist creating and insert a new vector
afos = new FileOutputStream(f);
aoos = new ObjectOutputStream(afos);
Vector<Doctor> v = new Vector<Doctor>();
v.add(D);
aoos.writeObject(v);
} else { // Extract the existing vector and add the object to it
FileInputStream afis = new FileInputStream(f);
ObjectInputStream aois = new ObjectInputStream(afis);
Vector<Doctor> existing_v = (Vector<Doctor>) aois.readObject();
existing_v.add(D);
afos = new FileOutputStream(f);
aoos = new ObjectOutputStream(afos);
aoos.writeObject(existing_v);
aois.close();
afis.close();
}
System.out.println("\n\nSuccessfully added " + D.name);
aoos.close();
afos.close();
}