import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}
case class stu (name:String,age:Int,sex:String) extends Serializable
object My_Serializable {
/**
* @param obj 输入的对象
* @tparam O 泛型,(输入对象的类型)
* @return 返回改对象的字节数组
*/
def serializ_ob[O](obj :O) ={
val byteArrayOutputStream = new ByteArrayOutputStream()
val stream = new ObjectOutputStream(byteArrayOutputStream)
stream.writeObject(obj)
stream.close()
byteArrayOutputStream.close()
byteArrayOutputStream.toByteArray
}
/**
* 反序列化,将字节数组反为对象
* @param array 该对象的字节数组
* @tparam O 该对象的类型
* @return 该对象
*/
def un_serializ_ob[O](array: Array[Byte]):O={
val stream = new ByteArrayInputStream(array)
val stream1 = new ObjectInputStream(stream)
stream.close()
stream1.readObject().asInstanceOf[O]
}
def main(args: Array[String]): Unit = {
val xm = stu("小明", 23, "男")
val bytes = serializ_ob[stu](xm)
println(bytes.mkString)
val value = un_serializ_ob[stu](bytes)
println(value)
}
}
scala 序列化与反序列化demo
最新推荐文章于 2024-04-26 22:04:53 发布
关键词由CSDN通过智能技术生成