Convert Any type in scala to Array[Byte] and back

前端 未结 2 1408
既然无缘
既然无缘 2020-12-09 09:24

I have the following question:

I have a variable value in my program which is declared as Any value.

I want to convert this value to Byte Array..

Ho

2条回答
  •  囚心锁ツ
    2020-12-09 09:58

    This should do what you need. It's pretty similar to how one would do it in 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)))
    }
    

提交回复
热议问题