Last active
August 20, 2017 14:22
-
-
Save yongjun823/1afe1ee74c9f44f40e62e5448cc2e2c0 to your computer and use it in GitHub Desktop.
java object serialize example for my friend
This file contains hidden or 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
| import java.io.Serializable; | |
| // custom data class | |
| // must implements Serializable | |
| public class MyData implements Serializable { | |
| int id; | |
| String name; | |
| MyData(int id, String name) { | |
| this.id = id; | |
| this.name = name; | |
| } | |
| } |
This file contains hidden or 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
| import java.io.FileInputStream; | |
| import java.io.FileNotFoundException; | |
| import java.io.IOException; | |
| import java.io.ObjectInputStream; | |
| import java.io.Serializable; | |
| // object read part | |
| // cast to custom class | |
| public class MyRead { | |
| public static void main(String[] args) | |
| throws IOException, FileNotFoundException, ClassCastException, ClassNotFoundException { | |
| FileInputStream fin = new FileInputStream("./my.ser"); | |
| ObjectInputStream ois = new ObjectInputStream(fin); | |
| for (int i = 0; i < 2; i++) { | |
| Object readData = ois.readObject(); | |
| if (readData == null) { | |
| System.out.println("no data"); | |
| } else { | |
| MyData data = (MyData) readData; | |
| System.out.println(data); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or 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
| import java.io.FileNotFoundException; | |
| import java.io.FileOutputStream; | |
| import java.io.IOException; | |
| import java.io.ObjectOutputStream; | |
| import java.io.Serializable; | |
| import java.util.ArrayList; | |
| // object write part | |
| public class MyWrite { | |
| public static void main(String[] args) throws IOException, FileNotFoundException { | |
| FileOutputStream stream = new FileOutputStream("./my.ser", true); | |
| ObjectOutputStream objectOutputStream = new ObjectOutputStream(stream); | |
| for (int i = 0; i < 3; i++) { | |
| objectOutputStream.writeObject(new MyData(10, "name")); | |
| } | |
| objectOutputStream.close(); | |
| stream.close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment