Skip to content

Instantly share code, notes, and snippets.

@SiAust
Created September 5, 2020 09:45
Show Gist options
  • Save SiAust/0a825be7ce5ac119bbd822a7722e1d7a to your computer and use it in GitHub Desktop.
Save SiAust/0a825be7ce5ac119bbd822a7722e1d7a to your computer and use it in GitHub Desktop.
Example of Serializing some classes.
import javax.imageio.IIOException;
import javax.swing.*;
import java.io.*;
public class HyperSkill {
public static void main(String[] args) {
Person simon = new Person("simon", 21, new Address("stillwater", "uk"));
String fileName = "C:\\users\\si_au\\desktop\\simon.data";
try {
SerializationUtils.serialize(simon, fileName);
Person deserializedSimon = (Person) SerializationUtils.deserialize(fileName);
System.out.println(deserializedSimon.getName());
System.out.println(deserializedSimon.getAddress().getStreet());
} catch (IOException | ClassNotFoundException e) {
System.out.println("some problem");
}
}
}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
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 void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void setName(String name) {
this.name = name;
}
}
class Address implements Serializable {
private static final long serialVersionUID = 564320375408842791L;
String street;
String country;
public Address(String street, String country) {
this.country = country;
this.street = street;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
class SerializationUtils {
/**
* Serialize the given object to the file
*/
public static void serialize(Object obj, String fileName) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
}
/**
* Deserialize to an object from the file
*/
public static Object deserialize(String fileName) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
ois.close();
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment