How to read and write Java object to a file

摘要: Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization.

Java object Serialization is an API provided by Java Library stack as a means to serialize Java objects. Serialization is a process to convert objects into a writable byte stream. Once converted into a byte-stream, these objects can be written to a file. The reverse process of this is called de-serialization.

A Java object is serializable if its class or any of its superclasses implement either the java.io.Serializable interface or its subinterface, java.io.Externalizable.

1. Java Object

Person.java
package com.mkyong;
import java.io.Serializable;
public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private int age;
	private String gender;
	Person() {
	};
	Person(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	@Override
	public String toString() {
		return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;

2. Writing and Reading objects in Java

The objects can be converted into byte-stream using java.io.ObjectOutputStream. In order to enable writing of objects into a file using ObjectOutputStream, it is mandatory that the concerned class implements Serializable interface as shown in the class definition below.

Reading objects in Java are similar to writing object using ObjectOutputStream

On reading objects, the ObjectInputStream directly tries to map all the attributes into the class into which we try to cast the read object. If it is unable to map the respective object exactly then it throws a ClassNotFound exception.

Let us now understand the writing and reading process using an example. We are using the Person class shown above as an object.

WriterReader.java
package com.mkyong;
package com.mkyong;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class WriterReader {
	public static void main(String[] args) {
		Person p1 = new Person("John", 30, "Male");
		Person p2 = new Person("Rachel", 25, "Female");
		try {
			FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
			ObjectOutputStream o = new ObjectOutputStream(f);
			// Write objects to file
			o.writeObject(p1);
			o.writeObject(p2);
			o.close();
			f.close();
			FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
			ObjectInputStream oi = new ObjectInputStream(fi);
			// Read objects
			Person pr1 = (Person) oi.readObject();
			Person pr2 = (Person) oi.readObject();
			System.out.println(pr1.toString());
			System.out.println(pr2.toString());
			oi.close();
			fi.close();
		} catch (FileNotFoundException e) {
			System.out.println("File not found");
		} catch (IOException e) {
			System.out.println("Error initializing stream");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

On executing the above code, we get below output:

Name:John
Age: 30
Gender: Male
Name:Rachel
Age: 25
Gender: Female

References

  1. Serialization Java Docs
  2. ObjectInputStream Java Docs
  3. ObjectOutputStream Java Docs

上一篇: Java Swing JFileChooser example
下一篇: Java 8 Filter a Map examples
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号