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?
Posted by Stephen Strowes on Wednesday, September 16th, 2009. You can follow me on twitter.
All content, including images, © Stephen D. Strowes, 2000–2016. Hosted by Digital Ocean.