Curriculum
In Java, ObjectInputStream
is a class that extends the InputStream
class and allows you to read objects from a file or input stream. It is used to deserialize objects that have been previously serialized using ObjectOutputStream
. Here is an example of how the ObjectInputStream
class is used in Java:
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class ObjectInputStreamExample { public static void main(String[] args) { try { FileInputStream fileInput = new FileInputStream("example.txt"); ObjectInputStream objectInput = new ObjectInputStream(fileInput); MyClass myObject = (MyClass) objectInput.readObject(); System.out.println(myObject.toString()); objectInput.close(); } catch (IOException | ClassNotFoundException e) { System.out.println("An error occurred while reading from the file: " + e.getMessage()); } } } class MyClass implements java.io.Serializable { private String name; private int age; public MyClass(String name, int age) { this.name = name; this.age = age; } public String toString() { return "Name: " + name + ", Age: " + age; } }
In this example, we create a FileInputStream
to a file named “example.txt”, and we use it to create an ObjectInputStream
. We read an object from the input stream using the readObject()
method and cast it to an instance of MyClass
, which is a class that implements the Serializable
interface. We print the contents of the object using the toString()
method and close the input stream using the close()
method.
The ObjectInputStream
class in Java has the following methods:
int available() throws IOException
: Returns the number of bytes that can be read from the input stream without blocking.int read() throws IOException
: Reads a single byte of data from the input stream.int read(byte[] buf) throws IOException
: Reads up to buf.length
bytes of data from the input stream into an array of bytes.int read(byte[] buf, int off, int len) throws IOException
: Reads up to len
bytes of data from the input stream into an array of bytes, starting at the specified offset off
.Object readObject() throws IOException, ClassNotFoundException
: Reads an object from the input stream and returns it.void close() throws IOException
: Closes the input stream and releases any system resources associated with it.Note that when reading objects from a file or input stream, it is important to ensure that the objects were serialized using ObjectOutputStream
and that the classes used in serialization and deserialization are compatible. Additionally, it is important to handle any potential exceptions that may be thrown when reading from the input stream.