How to read an object from file in Java (ObjectInputStream)
This example shows how to use ObjectInputStream
to read a serialized object from a file in Java, aka Deserialization.
public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException {
Object result = null;
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
result = ois.readObject();
}
return result;
}
// Convert byte[] to object, with deserialization filter, Java 9
public static Object convertBytesToObject(byte[] bytes, ObjectInputFilter filter) {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
// add filter before readObject
ois.setObjectInputFilter(filter);
return ois.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
Further Reading
1. Read serialized object from a file (ObjectInputStream)
The below example converts a Person
object to bytes stream and saves it into a file (Serialization). Later, it reads the bytes stream from the same file and converts it back to the original object (Deserialization).
package com.mkyong.io.object;
import java.io.Serializable;
import java.math.BigDecimal;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
// dun save this field into file
private transient BigDecimal salary;
//getters, setters, constructor
}
package com.mkyong.io.object;
import java.io.*;
import java.math.BigDecimal;
public class HelloSerializationFile {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("mkyong", 50, new BigDecimal(1000));
File file = new File("person.bin");
writeObjectToFile(person, file);
Person p = (Person) readObjectFromFile(file);
System.out.println(p);
}
// Serialization
// Save object into a file.
public static void writeObjectToFile(Person obj, File file) throws IOException {
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(obj);
oos.flush();
}
}
// Deserialization
// Get object from a file.
public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException {
Object result = null;
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
result = ois.readObject();
}
return result;
}
}
2. More Deserialization examples
// Deserialization
// Get object from a file.
public static Person readObject(File file) throws IOException, ClassNotFoundException {
Person result = null;
try (FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis)) {
result = (Person) ois.readObject();
}
return result;
}
// Deserialization
// generic example
@SuppressWarnings("unchecked")
public static <T> T readObject(InputStream is, Class<T> anyClass)
throws IOException, ClassNotFoundException {
T result = null;
try (ObjectInputStream ois = new ObjectInputStream(is)) {
result = (T) ois.readObject();
}
return result;
}
// Deserialization
// Convert object to byte[]
public static byte[] convertObjectToBytes(Object obj) {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
ois.writeObject(obj);
return boas.toByteArray();
} catch (IOException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
3. Java 9 Deserialization filters
In Java, deserialization from untrusted byte streams is extremely dangerous. So, Java 9 introduced deserialization filters to filter the incoming serialization data.
The below example shows how to use deserialization filters to only deserializing objects from com.mkyong.io.object.Person
and java.base/*
. Others all reject !*
.
package com.mkyong.io.object;
import java.io.*;
import java.math.BigDecimal;
public class HelloDeserializationFilter {
public static void main(String[] args) {
// this ok
//Person person = new Person("mkyong", 40, new BigDecimal(900));
// reject this Person2, only allow Person class
Person2 person = new Person2("mkyong", 40, new BigDecimal(900), "test");
byte[] bytes = convertObjectToBytes(person);
// only allow to deserialize com.mkyong.io.object.Person and java.base/*
// !* reject all
ObjectInputFilter filter =
ObjectInputFilter.Config.createFilter(
"com.mkyong.io.object.Person;java.base/*;!*");
Person p = (Person) convertBytesToObject(bytes, filter);
System.out.println(p);
}
// Convert object to byte[]
public static byte[] convertObjectToBytes(Object obj) {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
ois.writeObject(obj);
return boas.toByteArray();
} catch (IOException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
// Convert byte[] to object, with filter
public static Object convertBytesToObject(byte[] bytes, ObjectInputFilter filter) {
InputStream is = new ByteArrayInputStream(bytes);
try (ObjectInputStream ois = new ObjectInputStream(is)) {
// add filter before readObject
ois.setObjectInputFilter(filter);
return ois.readObject();
} catch (IOException | ClassNotFoundException ioe) {
ioe.printStackTrace();
}
throw new RuntimeException();
}
}
Output
java.io.InvalidClassException: filter status: REJECTED
at java.base/java.io.ObjectInputStream.filterCheck(ObjectInputStream.java:1412)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:2053)
at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1907)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2209)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1742)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:514)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:472)
at com.mkyong.io.object.HelloDeserializationFilter.convertBytesToObject(HelloDeserializationFilter.java:48)
at com.mkyong.io.object.HelloDeserializationFilter.main(HelloDeserializationFilter.java:23)
Exception in thread "main" java.lang.RuntimeException
at com.mkyong.io.object.HelloDeserializationFilter.convertBytesToObject(HelloDeserializationFilter.java:52)
at com.mkyong.io.object.HelloDeserializationFilter.main(HelloDeserializationFilter.java:23)
Further Reading
Download Source Code
$ git clone https://github.com/mkyong/core-java.git
$ cd java-io/com/mkyong/io/object
References
- JavaDoc ObjectInputStream
- Java Serialization and Deserialization examples
- How to write an object to file in Java (ObjectOutputStream)
- Serialization Filtering
- OWASP – Deserialization of untrusted data
- Brian Goetz – Towards Better Serialization
- Evil Pickles: DoS attacks based on Object-Graph Engineering
Hello Sir,
Nice post. Thanks for sharing the same.
Mkyong always bringing up the real world examples and a solution for it.
You help me a lot with your posts.
Thank you very much and keep up with your work.
Fantastic!!! I got many doubts using serializable… i got some horrible problems trying to load a file i saved from an arraylist full of objects, and this sounds like a good alternative to my problem, thank you man!