Read/Write Java Object to a File

In Java object can be read or written to a file using serialization and deserialization.


public class ObjectFileExample {

    public static void main(String[] args) {
        // Create an object to write to file
        User objectToWrite = new User("Mike", 32);

        // Write object to file
        writeObjectToFile(objectToWrite, "object.txt");

        // Read object from file
        User objectFromFile = readObjectFromFile("object.txt");
        System.out.println(STR."Object read from file: \{objectFromFile}");

    // Method to write object to file
    public static void writeObjectToFile(Object obj, String fileName) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
            System.out.println("Object successfully written to file.");
        } catch (IOException e) {

    // Method to read object from file
    public static User readObjectFromFile(String fileName) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
            return (User) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return null;

class User implements Serializable {
    private String name;
    private int age;

    public User(String name, int age) { = name;
        this.age = age;

    public String toString() {
        return STR."User {name='\{name}\{'\''}, age=\{age}\{'}'}";

Object successfully written to file.
Object read from file: User {name='Mike', age=32}

Written Object.txt File


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap