The ObjectInputStream class | Managing Input/Output Files in Java

The ObjectInputStream class

• Is part of the java.io package
• Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream
• Is a high-level class that can be used to read primitive values and serializable objects from a stream
• Has overloaded constructors but the most useful “chains” to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object
ObjectInputStream out = new ObjectInputStream(new FileInputStream(fd));
will construct a ObjectInputStream object chained to a FileInputStream object for reading primitive values and serializable objects from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch.
• Has many useful methods as follows:
Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details.
• Example. The following program can be used to read a file of array objects from disk. It can be used to display the array values stored by the previous sample program.
import java.io.*;
public class App
{
public static void main(String[] args)
{

// Local variables and object references.

File fd;
ObjectInputStream in;

// Get the path name from the user.

System.out.print(“Enter the file’s complete path name: “);
fd = new File(Keyboard.readString());

// Try to read data from the input stream.

try
{

// Open an input stream for the file.

in = new ObjectInputStream(new FileInputStream(fd));

// This loop reads a array objects from the stream and displays
// their contents. The loop ends when end of file is reached.

try
{
while (true)
{
String[] array = (String[]) in.readObject();
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
System.out.println(“<< END OF ARRAY >>”);
}
}
catch (EOFException e) {
System.out.println(“<< END OF FILE >>”);
}

// Close the stream.

in.close();
System.out.println(“Closed – ” + fd.getPath());
}

// Catch an IOException if one is thrown.

catch (IOException e) {
System.out.println(e.getMessage());
}

// Catch an ClassNotFoundException if one is thrown.

catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}

Scroll to Top