2

I am building a framework for my day-to-day tasks. I am programming in scala using a lot of type parameter.

Now my goal is to save datastructures to files (e.g. xml files). But I realized that it is not possible using xml files. As I am new to this kind of problem I am asking:

Is there a way to store the types of my datastructures in a file??? Is there a way in scala???

peri4n
  • 1,389
  • 13
  • 24
  • 1
    Did you have a look at serialization? You can use that with binary formats or with XML. – Kim Stebel Nov 28 '11 at 10:24
  • 2
    No. I did not have a look at serialization because I am completly new to the JVM technology. It may be a reason to look at this @serializable thing I never took care of. – peri4n Nov 28 '11 at 10:29
  • If keeping those files human-readable is not a requirement, than serialization would be your best option both in terms of implementation and performance. – Nikita Volkov Nov 28 '11 at 12:22
  • See also http://stackoverflow.com/questions/35785/xml-serialization-in-java – Kim Stebel Nov 28 '11 at 12:43
  • I have heard from people that they had good experiences with lift-json (http://www.assembla.com/spaces/liftweb/wiki/JSON_Support). However I don't know if it's a prerequisite that the objects it can persist must be case classes. – 0__ Nov 28 '11 at 13:25

1 Answers1

4

Okay guys. You did a great job basicly by naming the thing I searched for.

Its serialization.

With this in mind I searched the web and was completly astonished by this feature of java. Now I do something like:

object Serialize {

  def write[A](o: A): Array[Byte] = {
    val ba = new java.io.ByteArrayOutputStream(512)
    val out = new java.io.ObjectOutputStream(ba)
    out.writeObject(o)
    out.close()
    ba.toByteArray()
  }

  def read[A](buffer: Array[Byte]): A = {
    val in = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(buffer))
    in.readObject().asInstanceOf[A]
  }
}

The resulting Byte-Arrays can be written to a file and everthing works well.

And I am totaly fine that this solution is not human readable. If my mind changes someday. There are JSON-parser allover the web.

peri4n
  • 1,389
  • 13
  • 24