I am trying to use an ObjectOutputStream and an ObjectInputStream to store multiple BookLibrary objects in an ArrayList, but whenever I attempt to read in the data from the text file ("data.txt") that is supposed to contain the ArrayList information after stopping the program and running it again it gives me the above error on line 20 of the program. Here is the code at present:
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Driver {
public static ArrayList<BookLibrary> libraries;
public static ObjectOutputStream output;
public static ObjectInputStream input;
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception{
File file = new File("data.txt");
libraries = new ArrayList<BookLibrary>();
if (!file.exists()) {
file.createNewFile();
}
else {
try {
input = new ObjectInputStream(new FileInputStream(file));
System.out.println("before reading from file");
Driver.libraries = (ArrayList<BookLibrary>)input.readObject();
System.out.println("after reading from file");
} catch (EOFException e) {
System.out.println("end of file reached");
} finally {
if (input != null) {
input.close();
}
}
}
if (output == null) {
output = new ObjectOutputStream(new FileOutputStream(file));
}
Driver.update();
Frame frame = new Frame(Driver.libraries);
}
public static void update() {
try {
output.writeObject(libraries);
output.flush();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I have made sure that all of the classes are Serializable and even have the same serialVersionUID, and have deleted the data file several times to try to clear out any corrupted data. The only thing that I can think of at this point is that the ObjectOutputStream is causing problems whenever it is initialized. I am a complete beginner when it comes to file handling so I have no idea what could be causing this issue, and I couldn't find any information on how to fix this problem. Any help would be appreciated at this point. Thanks!
ObjectOutputStream. Otherwise it would start with hex AC. NB Serialized data is not text, and non-text data should not be saved in a file named.txt. NB (2) Thefile.createNewFile()line here is a complete waste of time and space..ser. It still gives me the wrong header whenever I initialize theObjectOutputStream. How can I be sure that theObjectOutputStreamis creating the file correctly?