老师,电话本项目作业,我在operate类的addOpration中添加了ObjectOutputStream,
public void addOperation() {
TelNoteRegex telNoteRegex=new TelNoteRegex();
String name=telNoteRegex.nameValidate();
String age=telNoteRegex.ageValidate();
String sex=telNoteRegex.sexValidate();
String telNum=telNoteRegex.telNumValidate();
String address=telNoteRegex.addressValidate();
Person person=new Person(name,age,sex,telNum,address);
this.list.add(person);
person.setId(this.list.size());
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("d:/person.txt",true)));
oos.writeObject(person);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (oos!= null) {
oos.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
然后在Operate类创建了一个ObjectInputStream方法,
/**
* 对象输入流
* 初始化list
*/
public void ObjectInputStream(){
ObjectInputStream ois=null;
try{
ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream("d:/person.txt")));
List list=(List<Person>)ois.readObject();
this.list=list;
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if (ois!=null){
ois.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
再在app类的start方法里调用operate的ObjectInputStream方法,初始化list内的信息,以便下次打开程序时读取之前存储的信息。
public void start(){
Menu menu=new Menu();
TelNoteRegex regex=new TelNoteRegex();
Operate operate=new Operate();
operate.ObjectInputStream();//初始化Operate中的list
while (true) {
menu.mainMenu();
int item=regex.menuItemValidate(1,6);
switch (item){
case 1:operate.addLogic();break;
case 2:operate.searchLogic();break;
case 3:operate.modifyLogic();break;
case 4:operate.deleteLogic();break;
case 5:operate.orderLogic();break;
case 6:System.exit(0); //结束虚拟机
程序运行后有如下报错。
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2638)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3113)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:853)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
at com.wxc.Operate.ObjectInputStream(Operate.java:159)
at com.wxc.App.start(App.java:28)
at com.wxc.App.main(App.java:18)
不知道这个思路问题出在哪里。