Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to Read Object from File

Ramesh Fadatare edited this page Jul 18, 2018 · 3 revisions

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

  1. 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

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /