Skip to content

Instantly share code, notes, and snippets.

@yanil3500
Last active November 29, 2018 16:58
Show Gist options
  • Save yanil3500/30bcde2a56939dc5ffbcfedb7b26d3af to your computer and use it in GitHub Desktop.
Save yanil3500/30bcde2a56939dc5ffbcfedb7b26d3af to your computer and use it in GitHub Desktop.
Serializing objects in Java
import java.io.*;
import java.util.ArrayList;
import java.util.stream.Stream;
class Car implements Serializable {
private String make;
private String model;
public Car(String make, String model) {
this.make = make;
this.model = model;
}
public Car() {
this("Mercedes-Benz", "C300");
}
}
class Person implements Serializable {
private String name;
private int age;
private Car car;
public Person(String name, int age) {
this.name = name;
this.age = age;
this.car = new Car();
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public int getAge() {
return age;
}
}
public class SerializingObjects {
public static void main(String[] args) {
Person p1 = new Person("Johnny", 55);
Person p2 = new Person("Arthur", 38);
p2.setCar(new Car("Audi", "A4"));
//This Stackoverflow question was referenced while serialization functionality was being implemented.
//https://stackoverflow.com/questions/12684072/eofexception-when-reading-files-with-objectinputstream
String fileName = "people.txt";
//Time to serialize
try (
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos)
) {
Stream.of(p1, p2, null).forEach(person ->
//NULL indicates the end of the stream (no more objects to send)
{
try {
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
//Time to deserialize
ArrayList<Person> people = new ArrayList<>();
try (
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
) {
Object o = ois.readObject();
while (o != null) {
people.add((Person) o);
o = ois.readObject();
}
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
people.stream().forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment