Object IO Stream
Object IO Stream:
Object Output Streams provides the functionality
to flatten out an Object Graph into serialized binary data and then uses a
primary Java IO Stream to write that data into a destination. Similarly an
Object Input Stream uses a primary Java IO Stream to read serialized binary
data from a source and then reconstructs the Object Graph over it. Object
Streams takes the responsibility of serializing or creating all the objects in
the graph.
Below is an example of ObjectOutputStream storing a HashMap Object into a File.
// Creating the HashMap Object to be serialized and stored in a File HashMap map = new HashMap(); map.put("1", "1"); // Creating an Object of ObjectOutputStream by passing a Primary IO Stream (FileOutputStream) ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("objectstream.txt")); //Writing the HashMap Object to the File; objectOutputStream.writeObject(map); // Flushing and Closing the Stream objectOutputStream.flush(); objectOutputStream.close();
Below is an example of ObjectInputStream, reading and populating the serialized Object (HashMap) from the File.
FileInputStream fileInputStream = new FileInputStream("objectstream.txt"); // Creating an Object of ObjectInputStream by passing a Primary IO Stream (FileInputStream) ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); HashMap map = null; Object eachObject = null; // Checking with the Primary IO Stream if Serialized Bytes avaliable in the File System.out.println(fileInputStream.available()); // Reading the Object eachObject = objectInputStream.readObject(); System.out.println(fileInputStream.available()); if (eachObject instanceof HashMap) { map = (HashMap)eachObject; } objectInputStream.close();
<< Array IO Stream | Piped IO Stream >> |
No comments:
Post a Comment