How to Read Object from File - RameshMF/java-io-guide GitHub Wiki
Overview
In this example, we will use ObjectInputStream Class to read employee object to file.
The deserialization process is quite similar with the serialization, you need to use ObjectInputStream to read the content of the file and convert it back to a Java object.
We can also read String, Arrays, Integer and Date from file using ObjectInputStream class because these classes are internally implements java.io.Serializable interface.
Read Object from File Example
- Let's first create Employee class and which implements java.io.Serializable interface.
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Let'employees.txt file under some directory write employee object into file using ObjectOutputStream class.
/**
* This Java program demonstrates how to read object from file.
* @author javaguides.net
*/
public class ObjectInputStreamExample {
public static void main(String[] args) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employees.txt"))) {
final Employee employee = (Employee) in.readObject();
System.out.println(" printing employee object details");
System.out.println(employee.getId() + " " + employee.getName());
System.out.println(" printing address object details");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output:
printing employee object details
100 ramesh
printing address object details
Reference
https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html