在java中将任何对象转换为字节数组 [英] Converting any object to a byte array in java

查看:145
本文介绍了在java中将任何对象转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个X类型的对象,我希望在将它发送到S3存储之前将其转换为字节数组。谁能告诉我怎么做?感谢您的帮助。

I have an object of type X which I want to convert into byte array before sending it to store in S3. Can anybody tell me how to do this? I appreciate your help.

推荐答案

您想要做的是系列化。有几种方法可以做到这一点,但如果你不需要任何想象,我想使用标准Java对象序列化会做得很好。

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

也许你可以使用这样的东西?

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

可以做一些改进。至少你不能每个字节数组读/写一个对象,这可能是你想要的,也可能不是你想要的。

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

请注意只有支持 java.io.Serializable 接口可以写入流(参见 java.io.ObjectOutputStream )。

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

由于你可能遇到它,所以 java.io.ByteArrayOutputStream 可能会成为瓶颈。根据您的线程模型,您可能需要考虑重用某些对象。

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

用于序列化未实现 Serializable 接口您需要编写自己的序列化程序,例如使用 java.io.DataOutputStream java.nio.ByteBuffer 也许与反射或拉入第三方依赖。

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

此网站一些序列化框架的列表和性能比较。查看API似乎 Kryo 可能符合您的需求。

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

这篇关于在java中将任何对象转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆