Last active
August 29, 2015 14:23
-
-
Save k8si/b75e8572c7fe33146a28 to your computer and use it in GitHub Desktop.
Serialization
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
import java.io._ | |
object TestStuff { | |
class Person(val name: String) extends Serializable { | |
var age: Int = 0 | |
object personProperties extends Serializable { | |
val location: String = "MA" | |
var job: String = "" | |
} | |
override def toString: String = s"Person(name:$name age:$age location:${personProperties.location} job:${personProperties.job})" | |
} | |
def serializePerson(p: Person): Unit = { | |
val fout = new FileOutputStream("tmp.ser"); val out = new ObjectOutputStream(fout) | |
out.writeObject(p) | |
out.close(); fout.close() | |
} | |
def deserializePerson(): Person = { | |
val fin = new FileInputStream("tmp.ser"); val in = new ObjectInputStream(fin) | |
val p: Person = in.readObject().asInstanceOf[Person] | |
in.close(); fin.close() | |
p | |
} | |
def main(args: Array[String]): Unit = { | |
val p = new Person("foo") | |
p.personProperties.job = "zookeeper" | |
println(s"serializing: $p") // serializing: Person(name:foo age:0 location:MA job:zookeeper) | |
serializePerson(p) | |
val newP = deserializePerson() | |
println(s"deserialized: $newP") // deserialized: Person(name:foo age:0 location:MA job:) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment