Write an Object to File in Java

Writing (or serializing) an object to a file in Java involves converting the object into a sequence of bytes and saving it. This is done using the ObjectOutputStream class. 

Before we dive into the code, ensure that the object's class (and any of its member objects) implements the Serializable interface. 

Here's a step-by-step guide:

1. Making the Class Serializable 

First, the class you wish to serialize and deserialize should implement the Serializable interface. Let's first create the Employee class and which implements the 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;
     }
}

2. Writing Object to File

To write an object to a file:
/**
 * 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();
          }
     }
}
In this code: 
A FileOutputStream is used to write bytes to a file. 

The ObjectOutputStream takes care of the serialization process and writes the serialized bytes to the file. 

The writeObject method of ObjectOutputStream is used to serialize and write the object. 

Proper exception handling is crucial as there's a potential for things to go wrong, e.g., file write permissions, disk space issues, etc. 

Conclusion 

Serialization in Java allows developers to write objects to a file easily, but it's vital to be aware of the potential implications. When serializing and deserializing, ensure to handle exceptions properly, be aware of versioning issues in classes, and always be cautious of security vulnerabilities, especially if dealing with data from untrusted sources.

References

Comments