Java:对象到字节 [] 和字节 [] 到对象转换器(用于东京内阁)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3736058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)
提问by volni
I need to convert objects to a byte[] to be stored in the Tokyo Cabinet key-value store. I also need to unbyte the byte[] to an Object when reading from the key-value store.
我需要将对象转换为 byte[] 以存储在 Tokyo Cabinet 键值存储中。从键值存储中读取时,我还需要将字节 [] 取消字节到对象。
Are there any packages out there that will help me with this task? Or would the best solution to implement it myself?
是否有任何软件包可以帮助我完成这项任务?或者自己实施它的最佳解决方案是什么?
采纳答案by Thomas Mueller
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
回答by G B
If your class extends Serializable
, you can write and read objects through a ByteArrayOutputStream
, that's what I usually do.
如果你的类 extends Serializable
,你可以通过 a 写入和读取对象ByteArrayOutputStream
,这就是我通常做的。
回答by Bozho
You can look at how Hector does this for Cassandra, where the goal is the same - convert everything to and from byte[]
in order to store/retrieve from a NoSQL database - see here. For the primitive types (+String), there are special Serializers, otherwise there is the generic ObjectSerializer
(expecting Serializable
, and using ObjectOutputStream
). You can, of course, use only it for everything, but there might be redundant meta-data in the serialized form.
您可以查看 Hector 如何为 Cassandra 执行此操作,目标是相同的 - 将所有内容相互转换byte[]
,以便从 NoSQL 数据库存储/检索 -请参见此处。对于原始类型(+String),有特殊的序列化器,否则有通用的ObjectSerializer
(期望Serializable
和使用ObjectOutputStream
)。当然,您可以只将它用于所有内容,但序列化形式中可能存在冗余元数据。
I guess you can copy the entire package and make use of it.
我想你可以复制整个包并使用它。
回答by SANN3
Use serialize
and deserialize
methods in SerializationUtils
from commons-lang.
来自commons-lang 的使用serialize
和deserialize
方法。SerializationUtils