如何将对象分解为byte []?

时间:2011-05-18 23:48:04

标签: java android object bytearray parcelable

如何破坏对象---更具体的Parcelable;实际上它是一个捆绑但是点相同 - 变成一个字节[]?我认为我这样做的方式很好,但显然我错了。

这里仅供参考,这是我正在做的旧方式。

public static byte[] getBytes(Object obj) throws java.io.IOException {
    ByteArrayOutputStream bos   = new ByteArrayOutputStream();
    ObjectOutputStream oos      = new ObjectOutputStream(bos);
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    bos.close();
    byte[] data = bos.toByteArray();
    return data;
}

谢谢~Aedon

编辑1 ::

打破像这样的对象将Bundle传递给它会导致NotSerializableException。

3 个答案:

答案 0 :(得分:4)

你的代码看起来很好。我建议如下:

public static byte[] getBytes(Serializable obj) throws IOException {
    ByteArrayOutputStream bos   = new ByteArrayOutputStream();
    ObjectOutputStream oos      = new ObjectOutputStream(bos);
    oos.writeObject(obj);

    byte[] data = bos.toByteArray();

    oos.close();
    return data;
}

答案 1 :(得分:1)

问题提到了Parcelable,它并不总是可序列化的。 我认为正确的方法是将Parcelable写入Parcel。 然后使用Parcel的marshall()方法写出原始字节。

我玩了一点。如果您的Parcelable遵循协议,则以下代码会为Parcelable写出正确的字节数组。假设MyParcelable包含2个字符串和1个int。

            Parcel parcel1 = Parcel.obtain();
            MyParcelable parcelable1 = new MyParcelable("a", "b", 25);
            parcelable1.writeToParcel(parcel1, 0);

            byte content[] = parcel1.marshall();
            parcel1.recycle();
            Parcel parcel2 = Parcel.obtain();
            parcel2.unmarshall(content, 0, content.length);
            parcel2.setDataPosition(0);
            MyParcelable parcelable2 = MyParcelable.CREATOR.createFromParcel(parcel2);
            parcel2.recycle();
            Toast.makeText(context, parcelable2.a + " " + parcelable2.b + " " + parcelable2.val, Toast.LENGTH_LONG).show();

另见How to use Parcel in Android?

答案 2 :(得分:0)

使用Okio库,它可以替代ByteArrayOutputStream,并具有更强大的API。

public static byte[] getBytes(Serializable obj) throws IOException {
    Buffer buffer = new Buffer();
    ObjectOutputStream objectOut = new ObjectOutputStream(buffer.outputStream());
    objectOut.writeObject(obj);
    objectOut.close();
    return buffer.readByteArray();
}