Skip to content

Instantly share code, notes, and snippets.

@cosminpopescu14
Created August 19, 2018 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosminpopescu14/ed3ac53a0dba0465665c7bac23dd4a78 to your computer and use it in GitHub Desktop.
Save cosminpopescu14/ed3ac53a0dba0465665c7bac23dd4a78 to your computer and use it in GitHub Desktop.
Java serialize and unserialize object
package com.company;
public class DemoSerialize implements java.io.Serializable
{
public int a;
public String b;
public DemoSerialize(int _a, String _b)
{
this.a = _a;
this.b = _b;
}
}
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args)
{
// write your code here
DemoSerialize demoSerialize = new DemoSerialize(12, "abcd");
var fileName = "object.ser";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
outputStream.writeObject(demoSerialize);
outputStream.close();
System.out.println("object serialized. check file");
}
catch (IOException ex)
{
ex.printStackTrace();
}
DemoSerialize demoSerializeObj = null;
//try with resources
try(var fileInput = new FileInputStream(fileName);
var outputStream = new ObjectInputStream(fileInput)
)
{
demoSerializeObj = (DemoSerialize)outputStream.readObject();
System.out.println("object deserialize");
System.out.println("a = " + demoSerializeObj.a);
System.out.println("b = " + demoSerializeObj.b);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch (ClassNotFoundException cnfeEx)
{
cnfeEx.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment