Object (de)serlialisation to/from file in Scala
This wasn’t as simple as I expected it to be. It’s easy to dump objects file in a human-readable format (via java.io.FileWriter), later reading and parsing the Strings back into Objects. But “proper” serialisation is a bit trickier, and not especially well-documented. After a bit of poking around, my working solution is this:
To write:
import scala.actors.remote.JavaSerializer
import java.io.DataOutputStream
import java.io.FileOutputStream
val js = new JavaSerializer(null, null)
val os = new DataOutputStream(new FileOutputStream("foo"))
val list = List(1,2,3)
println(list(2))
js.writeObject(os, list)
os.close()
And, to read:
import scala.actors.remote.JavaSerializer
import java.io.DataInputStream
import java.io.FileInputStream
val js = new JavaSerializer(null, null)
val is = new DataInputStream(new FileInputStream("foo"))
val list = js.readObject(is).asInstanceOf[List[Int]]
println(list(2))
is.close()
That feels a bit hackish though. Perhaps there’s a neater way of doing this?
2 comments
[...] up my previous post on object serlialisation and deserialisation, a minor gotcha: Passing ‘null’ as the [...]
Just wanted to ask you, if you are aware of what the first parameter (service: Service) of JavaSerializer stands for? Currently I am able to find the only one subclass, namely, TcpService which is (just as like the JavaSerializer itself) totaly undocumented. Concerning the names of it’s methods this one seems not as what I need, if I want to serialize/deserialize Scala-objects in order to send them over JGroups channel.