现在scala.util.Marshal已被删除,并且创新的Pickling库似乎不受支持(需要使用Scala 2.10.4)。
示例:
val myObj = SortedSet(20, 10, 30)
SomeUtil.saveToFile(myObj)
//...later:
val restored: SortedSet[Int] = SomeUtil.restoreFromFile(filename)
答案 0 :(得分:1)
这适用于Scala 2.11.1,但比我对现代类库的预期要麻烦得多:
def saveToFile (obj: Object, filename: String) = {
val out = new FileOutputStream(new File(filename));
try {
out.write(Serializer.serialize(obj))
}
finally {
out.close();
}
}
def restoreFromFile[T] (filename: String): Option[T] = {
try {
val file = new FileInputStream(filename)
val in = Stream.continually(file.read).takeWhile(-1 !=).map(_.toByte).toArray
Some(Serializer.deserialize(in).get)
}
catch {
case _: Exception => None
}
}
def serialize[T] (obj: T): Array[Byte] = { // use instead of Marshal.dump in Scala 2.11
val byteStream = new ByteArrayOutputStream()
val out = new ObjectOutputStream(byteStream)
out.writeObject(obj)
out.close()
byteStream.toByteArray
}
def deserialize[T] (data: Array[Byte]): Try[T] = { // use instead of Marshal.load in Scala 2.11
if (data == null)
Failure(new NullPointerException())
else {
val in = new ObjectInputStream(new ByteArrayInputStream(data))
try {
Success(in.readObject.asInstanceOf[T])
}
catch {
case e: Exception => Failure(e)
}
finally {
in.close()
}
}
}
}
答案 1 :(得分:1)
更简单的方法是使用Java类:ObjectInputStream和ObjectOutputStream。
使用@SerialVersionUID标记您的自定义类:
@SerialVersionUID(1L)
class MyClass extends Serializable {...}
val out = new ObjectOutputStream(new FileOutputStream(new File(filename)))
out.writeObject(this)
out.close
val in = new ObjectInputStream(new FileInputStream(new File(filename)))
val myInstance = in.readObject().asInstanceOf[MyClass]
in.close