Created
August 19, 2018 09:46
-
-
Save cosminpopescu14/ed3ac53a0dba0465665c7bac23dd4a78 to your computer and use it in GitHub Desktop.
Java serialize and unserialize object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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