Created
April 22, 2015 05:20
-
-
Save trumanw/0e8c7b8c9de508c01d60 to your computer and use it in GitHub Desktop.
Serialization demo in scala
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._ | |
| @SerialVersionUID(124L) | |
| class Person(var name: String) | |
| extends Serializable { | |
| override def toString = f"My name is $name%s." | |
| } | |
| @SerialVersionUID(123L) | |
| class Pet(var name: String, var species: String, var owner: Person) | |
| extends Serializable { | |
| override def toString = { | |
| val ownerName = owner.name | |
| f"$ownerName%s has a $species%s named $name%s" | |
| } | |
| } | |
| object SerializationDemo extends App { | |
| // init person and pet | |
| val person = new Person("Truman Wu") | |
| val pet = new Pet("Jojo", "dog", person) | |
| // serialize two associated objects into the tmp file | |
| val oos = new ObjectOutputStream(new FileOutputStream("./pets2persons")) | |
| oos.writeObject(person) | |
| oos.writeObject(pet) | |
| oos.close | |
| // deserialize the two objects from the file created above | |
| val ois = new ObjectInputStream(new FileInputStream("./pets2persons")) | |
| val personOutput = ois.readObject() | |
| val petOutput = ois.readObject() | |
| ois.close | |
| println(personOutput) | |
| println(petOutput) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment