I know that this question may be answered, but I can't find a solution.
I have a book class and I create objects. What I want is that each time I create an object, it is saved to a file books.txt
. I also need to be able to open this file and read it at any time and be able to search an object by its parameters ex::(String name)
. I have read a lot of topics but I can't find a solution.
When I try to open my file and search for the objects, the first object is being printed fine, but when it opens the second object it gives me errors like:
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)
Code:
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();
}
}
Search function:
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;
}
}