How to write an Object to file in Java - RameshMF/java-io-guide GitHub Wiki
Overview
In this example, we will use ObjectOutputStream Class to write employee object to file.
- To write or send object to external world the object must implements java.io.Serializable interface type.
- It means this objects class must be a sub class of java.io.Serializable interface, else write() method throws java.io.NotSerializableException.
- The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
We can also write String, Arrays, Integer and date to file using ObjectOutputStream class because these classes are internally implements java.io.Serializable interface.
Write an Object to 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's create employees.txt file under some directory. Write code to write employee object to file employees.txt.
/**
* This Java program demonstrates how to write object in file.
* @author javaguides.net
*/
public class ObjectOutputStreamExample {
public static void main(String[] args) {
final Employee employee = new Employee();
employee.setId(100);
employee.setName("ramesh");
try (final FileOutputStream fout = new FileOutputStream("employees.txt");
final ObjectOutputStream out = new ObjectOutputStream(fout)) {
out.writeObject(employee);
out.flush();
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reference
https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html