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.
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
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 ObjectOutputStreamObjectInputStream
. Below example shows the complete cycle of writing objects and reading objects in Java.
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.
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
great tutorial that is easy to understand for beginners
Oh my God, you have the best tutorials out of everyone on the first search result page of Google. Awesome!
Thanks a lot for providing the easiest to understand tutorial on the web!
If i open the app, store some data and closing that app…when i return to the app, i need to resume my work…how to achieve this? Please explain
Save it to a file….then read it back when the app is re-opened
Suppose I wrote some serialized content to a file and then later on I want to read it using deserialization but before reading it some of the values of the actual object that I wrote to file have been changed. How can I handle this so that the object and file are always in sync. Do I need to keep writing to file again and again or is there any other alternative ?
this is very good!! thanks!!
how can I use only one object, to write multiple states of one objects in a file.
like using a for loop.
eg:
for(int I=0;I<3;i++){
// initialise p1 here.
o.writeobject(p1);
}
is there a way to do it like this.
simple and to the point, kudos
What if i want to store multiple objects from arraylist of objects and read multiple objects into arraylist of objects?
can someone please modify the program?
we’ll use serialization mostly over the network not in local 🙂
Do we have any example over network(Data transmission)
This code was working for me, then it decided to throw the IOException for the ObjectInputStream, do you know why this could occur?
Don’t know if it is because the object variables (fields) are all in lowercase when the object is serializing them with first letters in uppercase… How it will assoc them right when unserializing?
Looks like it’s more convenient using native Property read/write mechanisms (since JDK 1.0)…
You need to implement Serializable in your object class.
This could be much more useful to show how an object that is NOT serializable can be written to file then read back in another JVM. This is just calling the toString method and outputting that to a file. If the object changes and the toString does not get updated, data will be loss. Plus you will have to parse the string to read it like this.
I often encounter java classes in external sources that I can not just annotate as serializable. There are complex objects that would save a lot of time when I just dump the JSON into a file, make a small change, then reboot the project and import that complex object.
how can you find a person from the file by their name
Take the file into your program and then search through it