import java.io.{FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream}
object D02_序列化和反序列化 {
// Scala中实现序列化和反序列化操作需要继承Serializable特质
// class Person(var name: String, var age: Int) extends Serializable
// 样例类自动继承了Serializable特质
case class Person(var name: String, var age: Int)
def main(args: Array[String]): Unit = {
serialize()
deserialize()
}
// 序列化:将对象转换为二进制数据写入到文件中
def serialize(): Unit = {
val p = new Person("张三", 25)
val oos = new ObjectOutputStream(new FileOutputStream("./data/6.txt"))
oos.writeObject(p)
oos.close()
}
// 反序列化:从文件中读取对象
def deserialize(): Unit = {
val ois = new ObjectInputStream(new FileInputStream("./data/6.txt"))
val p: Person = ois.readObject().asInstanceOf[Person]
println(p.name, p.age)
ois.close()
}
}
scala IO序列化和反序列化
最新推荐文章于 2023-08-08 21:33:45 发布