So I have a working ObjectOutputStream in a method that I start by calling the method in main. I need to then read the file it created and print out all 5 objects in it. Right now I'm only printing out the first object.
public static AccountSerializable serializReadObject() throws ClassNotFoundException, IOException {
AccountSerializable read = null;
try { // Create an input stream for file accounts.ser
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
read = (AccountSerializable) input.readObject();
input.close();
} catch (IOException i) {
throw i;
}catch(ClassNotFoundException c){
throw c;
}
return read;
}
public static void main(String[] args) {
try {
System.out.println(serializReadObject());
} catch (ClassNotFoundException | IOException e) {
System.out.println("Class not found");
e.printStackTrace();
}
}
I've tried to throw
boolean eof = false;
while(!eof){
try{
//read data
}catch(EOFException e){
eof = true;
}
}
in serializReadObject To loop it and I've also tried to instead catch it in main but I keep getting an error stating "Unreachable catch block for EOFException it is already handled by the catch block" I then tried to take away the IOException and just put EOFEception but alas it keeps forcing me to surround my read with IOException. Is there another way to loop this with EOF?
You're only getting the first object because your opening and closing the stream on each call. There are many ways to achieve what you want. One way is to use a List<AccountSerializable>
:
public static List<AccountSerializable> serializeReadObjects() throws IOException, ClassNotFoundException {
// create an input stream for file accounts.ser
// this line will throw an IOException if something goes wrong
// we don't need to catch it in this method though
ObjectInputStream input = new ObjectInputStream(new FileInputStream("accounts.ser"));
// create list to hold read in accounts
List<AccountSerializable> accounts = new ArrayList<>();
// keep reading until EOFException is thrown
boolean keepReading = true;
while(keepReading) {
try {
// read in serialized account
AccountSerializable read = (AccountSerializable) input.readObject();
// add read in serialized account to the list
accounts.add(read);
} catch(EOFException eofe) {
// we are at the end of file, so stop reading
keepReading = false;
input.close();
} catch(IOException ioe) {
// input stream error other than EOF, not sure what to do
input.close();
throw ioe;
} catch(ClassNotFoundException cnfe) {
// not sure what to do in this case, so close input
input.close();
throw cnfe;
}
}
return accounts;
}
public static void main(String[] args) {
List<AccountSerializable> accounts = null;
try {
// get list of read in accounts
accounts = serializeReadObjects();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
// iterate over list of read in accounts and output them to stdout
for(AccountSerializable account : accounts) {
System.out.println(account);
}
}