我知道这个问题可以回答,但我无法找到解决方案。
我有一个书类,我创建了对象。我想要的是每次创建对象时,它都会保存到文件books.txt
。我还需要能够打开此文件并随时阅读它,并能够通过参数ex::(String name)
搜索对象。我已经阅读了很多主题但我无法找到解决方案。
当我尝试打开文件并搜索对象时,第一个对象打印正常,但是当它打开第二个对象时,它会给我一些错误:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1379)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at Search.deserialzeBookName(Search.java:80)
at Search$1.actionPerformed(Search.java:58)
代码:
public void saveAll() {
int day = Integer.parseInt(arrDay.getText());
int month = Integer.parseInt(arrMonth.getText());
int year = Integer.parseInt(arrYear.getText());
this.date1 = new GregorianCalendar(year, month, day).getTime();
day = Integer.parseInt(deppDay.getText());
month = Integer.parseInt(deppMonth.getText());
year = Integer.parseInt(deppYear.getText());
this.date2 = new GregorianCalendar(year, month, day).getTime();
//System.out.println(date1);v
Book b;
b = new Book(onoma.getText(), epitheto.getText(), tilefono.getText(), date1, date2, toType(domatio.getText()), check());//dates
File f = new File ("books.txt");
try {
FileOutputStream fout = new FileOutputStream("books.txt",true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(b);
oos.close();
System.out.println("Done");
} catch (FileNotFoundException e) {
System.err.println("FileNotFound error");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOException error");
e.printStackTrace();
}
}
搜索功能:
public Book deserialzeBookName(){
Book address;
try{
FileInputStream fin = new FileInputStream("books.txt");
ObjectInputStream ois = new ObjectInputStream(fin);
while((address =(Book) ois.readObject()) !=null){
System.out.println(address);
}
ois.close();
//address = (Book) ois.readObject();
//ois.close();
return address;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}