Java serialization example

Leo 52 Published: 12/20/2024

Java serialization example

Here is a simple Java serialization example:

Person class

import java.io.Serializable;

public class Person implements Serializable {

private String name;

private int age;

private Address address;

public Person(String name, int age, Address address) {

this.name = name;

this.age = age;

this.address = address;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public Address getAddress() {

return address;

}

}

Address class

public class Address {

private String street;

private String city;

private String state;

private String zip;

public Address(String street, String city, String state, String zip) {

this.street = street;

this.city = city;

this.state = state;

this.zip = zip;

}

public String getStreet() {

return street;

}

public String getCity() {

return city;

}

public String getState() {

return state;

}

public String getZip() {

return zip;

}

}

Serialization example

import java.io.*;

public class SerializationExample {

public static void main(String[] args) throws IOException {

// Create a Person object

Person person = new Person("John Doe", 30, new Address("123 Main St", "Anytown", "CA", "94506"));

// Open an output stream to write the Person object to a file

FileOutputStream fileOutputStream = new FileOutputStream("person.ser");

ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

// Write the Person object to the file

objectOutputStream.writeObject(person);

objectOutputStream.flush();

objectOutputStream.close();

fileOutputStream.close();

System.out.println("Person serialized successfully!");

}

}

Deserialization example

import java.io.*;

public class DeserializationExample {

public static void main(String[] args) throws IOException, ClassNotFoundException {

// Open an input stream to read the Person object from a file

FileInputStream fileInputStream = new FileInputStream("person.ser");

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

// Read the Person object from the file

Person person = (Person) objectInputStream.readObject();

System.out.println("Name: " + person.getName());

System.out.println("Age: " + person.getAge());

System.out.println("Address: " + person.getAddress().getStreet() + ", " + person.getAddress().getCity() + ", " + person.getAddress().getState() + " " + person.getAddress().getZip());

objectInputStream.close();

fileInputStream.close();

System.out.println("Person deserialized successfully!");

}

}

In this example, we have a Person class with attributes name, age, and address. We also have an Address class with attributes street, city, state, and zip.

The serialization example demonstrates how to write a Person object to a file using the ObjectOutputStream class. The writeObject() method is used to serialize the Person object, and the flush() and close() methods are used to ensure that the output stream is properly closed.

The deserialization example demonstrates how to read a Person object from a file using the ObjectInputStream class. The readObject() method is used to deserialize the Person object, and the close() method is used to ensure that the input stream is properly closed.

Note that in both examples, we use the Serializable interface in the Person class to indicate that it can be serialized. We also need to close the output streams after writing the object, and the input streams after reading the object.

Java serialization example

Here's a Java serialization example:

Serialization is the process of converting an object into a byte stream that can be written to a file, network connection, or any other data storage system. This allows objects to be converted into a format that can be easily transmitted and reconstructed on another computer or device.

In this example, we will create a simple Java class called "Person" with two attributes: name and age. We will then serialize an instance of this class using the java.io.Serializable interface.

Here is the code:

import java.io.*;

// Define a Person class that implements Serializable

public class Person implements Serializable {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

// Getters and setters for the attributes

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

}

// Create an instance of the Person class

Person person = new Person("John Doe", 30);

// Serialize the object to a file

try (FileOutputStream fos = new FileOutputStream("person.ser")) {

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(person);

} catch (IOException e) {

System.out.println("Error serializing: " + e.getMessage());

}

// Deserialize the object from the file

try (FileInputStream fis = new FileInputStream("person.ser")) {

ObjectInputStream ois = new ObjectInputStream(fis);

Person deserializedPerson = (Person) ois.readObject();

System.out.println("Deserialized person: " + deserializedPerson.getName() + ", Age: " + deserializedPerson.getAge());

} catch (IOException e) {

System.out.println("Error deserializing: " + e.getMessage());

}

In this example, we first define a Person class that implements the Serializable interface. This means that the Person object can be converted into a byte stream and written to a file or other data storage system.

We then create an instance of the Person class with a name "John Doe" and age 30.

Next, we serialize the Person object to a file called "person.ser". We use the ObjectOutputStream class to write the object to the file. This is done by calling the writeObject() method and passing in the Person object as an argument.

Finally, we deserialize the Person object from the file using the ObjectInputStream class. We read the object back into memory by calling the readObject() method and casting it to a Person object.

Note that when we deserialize the object, we need to cast the result to a Person object using the (Person) syntax. This is because the readObject() method returns an Object, which needs to be cast to the correct type (in this case, Person) in order to access its attributes.

In conclusion, serialization allows objects to be converted into a byte stream that can be easily transmitted and reconstructed on another computer or device. In this example, we have seen how to serialize and deserialize a simple Java class called "Person" using the Serializable interface and ObjectOutputStream/ObjectInputStream classes.