I am currently preparing for an evaluation for a Job Offer i have. So the company has given some practice assignments and their respective Solutions.
I am facing a bit of dilemma on how to deserialize multiple objects from a Serialized file.
Initially when i was solving on my own, after studying the class definitions for FileInputStream and ObjectInputStream i figured the best way to achieve that would be.
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
while(fis.available()!=0)
{
obj = (Show)ois.readObject();
lst.add(obj);
}
ois.close();
fis.close();
But later when i searched , i didn't find anyone suggesting this, Though this worked perfectly for me. The Companies' Solution to the Assignment is
in=new ObjectInputStream(new FileInputStream(fileName));
Show s=null;
while((s=(Show)in.readObject())!=null){
list.add(s);
}
But when i try to use the latter solution in another program it gives me an Exception
FileInputStream fis = new FileInputStream(fileNameChannel);
ObjectInputStream ois = new ObjectInputStream(fis);
while((obj=(Channel) ois.readObject())!=null){
list.add(obj);
}
fis.close();
ois.close();
Exception:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.psl.util.SetTopBoxManagementSystemImpl.populateByChannelCategory(SetTopBoxManagementSystemImpl.java:29)
at com.psl.main.Client.main(Client.java:18)
To find a proper answer i tried searching over StackExchange and found people were actually suggesting in catching the exception and Handling it in combination with using While(true). - Link
What i couldn't understand is
- Why shouldn't I use fis.available()>0 ? or rather why doesn't anyone?
- What might be the possible reasons that the same implementation is resulting in an EOFException in one program but not in the other? Since both are extracting all the serialized objects present in the Serialized file.
- Why should I consider using while(true) and catching EOFException, if it is possible for me to implement in a way that no Exception would occur as long as everything is All right? It just seems like a shortcut for achieving. If something does go wrong(EOF wise) , how would we tackle that?
availableto return0even though we haven't read all the data we want too. I think they may be writing a null object to indicate the end of file.