2021-04-01

ObjectInputStream loop EOFException handling

 





Method#1


FileInputStream fis = new FileInputStream("input-file.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
 
while(fis.available() > 0) {
  Object obj = ois.readObject()
  ...
}





Method#2




...

         //write instance of EofIndicatorClass at EOF
         oout.writeObject(new EofIndicatorClass());


...

          /*
         *If oin.readObject() returns instanceof EofIndicatorClass that means
         *it's EOF, exit while loop and EOFException will not be thrown.
         */
         Object obj;
         while(!((obj =  oin.readObject()) instanceof EofIndicatorClass)){
             System.out.println(obj);
         }


...














No comments:

Google Referrals