Wednesday, May 27, 2009

Reading objects from file using ObjectInputStream

This example shows how to read objects that has been serialized to a file with an ObjectOutputStream.
We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.
The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached.
One could as well write 'while (true)' but as that is not good practice we won't do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop.
What this code example does instead is to catch the EOFException and just print out that the end of file is reached.
The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.
 
 
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectInputStream class
*/
public void readPersons(String filename) {
ObjectInputStream inputStream = null;
try {
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new FileInputStream(filename));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Person) {
System.out.println(((Person)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().readPersons("myFile.txt");
}
}
The output from the code above looks like this:
James
Ryan
19
Obi-wan
Kenobi
30
End of file reached.
 
 

No comments: