Reading/Writing Objects
Java object serialization
Serialization is the conversion of an object to a series of bytes , so that the object can be easily saved to persistent storage or streamed even across other platform or network. The same byte stream can then be deserialized - converted into a replica of the original object. As byte stream create is platform neutral hence once objects created in one system can be deserialized in other platform. It is very useful when you want to transmit one object data across the network, for instance from one JVM to another. Here in Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable. Example
import java.io.*;
class Student implements java.io.Serializable{
int ID;
String Name;
Student(int ID, String Name){
this.ID = ID;
this.Name=Name;
}
}
How to read and write Java object from/to a file?
The ObjectOutputStream is used to serialize it and write to a file, while ObjectInputStream can be used in a similar way to read the serialized objects back from file Example
import java.util.*;
import java.io.*;
class Student implements java.io.Serializable {
int ID;
String Name;
Student(int ID, String Name){
this.ID = ID;
this.Name=Name;
}
public String toString() {
return "ID:" + ID + "\nName: " + Name;
}
}
public class TestClass{
public static void main(String[] args) {
Student st1 = new Student(100, "Bill");
Student st2 = new Student(101, "Gates");
//writing Object to file
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\javaObjects.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
// Write objects to file
oos.writeObject(st1);
oos.writeObject(st2);
oos.close();
fos.close();
}
catch (IOException e){
e.printStackTrace();
}
//Read objects from file
try{
FileInputStream fis = new FileInputStream(new File("D:\\javaObjects.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
Student s1 = (Student) ois.readObject();
Student s2 = (Student) ois.readObject();
System.out.println(s1.toString());
System.out.println(s2.toString());
fis.close();
ois.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Related Topics