How to Read and Write Objects to a File in Java


First, the example will prompt user to specify a class user that must implement the Serializable interface, and define two methods storeObject() and readObject(), in the test class. An ObjectOutputStream object is used to write to a file and an ObjectInputStream object is used to read objects from a file.

Source Code

– user class

 package com.beginner.examples;

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = 22L;

	private String name;

	private int age;

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {

		return "name:" + name+"t"+"age:"+age;
	}

}
 

– Test class

 package com.beginner.examples;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

	public static void main(String[] args) {

		User u1 = new User("Tom", 22);
		
		//store
		storeObject(u1);
		//read
		readObject();

	}

	//This method is used to save objects to a file
	public static void storeObject(User user) {

		ObjectOutputStream objectOut = null;

		try {
			//Create an ObjectOutputStream object to write an object to a file
			objectOut = new ObjectOutputStream(new FileOutputStream("object.txt"));
			
			objectOut.writeObject(user);

		} catch (IOException e) {

			e.printStackTrace();
		} finally {
			if (objectOut != null) {
				try {
					objectOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	//Read an object from a file
	public static void readObject() {

		ObjectInputStream readObject = null;

		try {
			//Create an ObjectInputStream object to read objects in a file
			readObject = new ObjectInputStream(new FileInputStream("object.txt"));

			Object object = readObject.readObject();
	
			//print this object
			System.out.println(object);

			readObject.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}

Output:

 name:Tom	age:22

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments