gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:13:09 38 4
gpt4 key购买 nike

我有以下问题:

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

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

如何序列化为字节数组并返回?我发现了与其他类型(例如Double或Int)有关的示例,但不是Any。

最佳答案

这应该做您需要的。这与用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)))
}

关于scala - 将scala中的任何类型转换为Array [Byte]并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39369319/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com