将scala中的任何类型转换为Array [Byte]并返回

Ect*_*ras 19 serialization scala

我有以下问题:

我的程序中有一个变量值,声明为Any值.

我想将此值转换为字节数组..

如何序列化为字节数组并返回?我找到了与其他类型相关的示例,如Double或Int,但不是Any.

Bru*_*owe 24

这应该做你需要的.它与人们在Java中的表现方式非常相似.

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}

object Serialization extends App {

  def serialise(value: Any): Array[Byte] = {
    val stream: ByteArrayOutputStream = new ByteArrayOutputStream()
    val oos = new ObjectOutputStream(stream)
    oos.writeObject(value)
    oos.close()
    stream.toByteArray
  }

  def deserialise(bytes: Array[Byte]): Any = {
    val ois = new ObjectInputStream(new ByteArrayInputStream(bytes))
    val value = ois.readObject
    ois.close()
    value
  }

  println(deserialise(serialise("My Test")))
  println(deserialise(serialise(List(1))))
  println(deserialise(serialise(Map(1 -> 2))))
  println(deserialise(serialise(1)))
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`ois.close()`等 - 对于不改变状态的方法,应保留无括号表示法. (2认同)