【问题标题】:Persist/Restore Scala Instance (to/from File)持久化/恢复 Scala 实例(到/从文件)
【发布时间】:2014-05-29 21:34:02
【问题描述】:
在 Scala 中将实例保存到文件/从文件中恢复/恢复的最简单方法是什么?
现在 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)
【问题讨论】:
标签:
scala
serialization
marshalling
【解决方案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();
}
}
restoreFromFile
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()
}
}
}
}
【解决方案2】:
更简单的方法是使用 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