簡體   English   中英

將任何 object 轉換為 java 中的字節數組

[英]Converting any object to a byte array in java

我有一個 X 類型的 object,我想在將其發送到 S3 之前將其轉換為字節數組。 誰能告訴我該怎么做? 我感謝您的幫助。

您要做的就是所謂的“序列化”。 有幾種方法可以做到這一點,但如果你不需要任何花哨的東西,我認為使用標准 Java object 序列化就可以了。

也許你可以使用這樣的東西?

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();
            }
        }
    }

}

可以對此進行一些改進。 至少你只能讀/寫每個字節數組一個 object 的事實,這可能是也可能不是你想要的。

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

由於您可能會遇到它,因此java.io.ByteArrayOutputStream的連續分配和調整大小可能會成為瓶頸。 根據您的線程 model 您可能需要考慮重用一些對象。

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 ofjava.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer也許與反射一起,或者引入第三方依賴。

這個站點有一些序列化框架的列表和性能比較。 查看 API 似乎Kryo可能適合您的需要。

commons-langSerializationUtils中使用serializedeserialize化方法。

是的。 只需使用二進制序列化 您必須讓每個 object 使用implements Serializable但從那里開始很簡單。

如果您想避免實現 Serializable 接口,您的另一種選擇是使用反射並使用下面的過程從緩沖區讀取和寫入數據:

/** 
 * Sets all int fields in an object to 0.
 *
 * @param obj The object to operate on.
 *
 * @throws RuntimeException If there is a reflection problem.
 */
 public static void initPublicIntFields(final Object obj) {
    try {
       Field[] fields = obj.getClass().getFields();
       for (int idx = 0; idx < fields.length; idx++) {
          if (fields[idx].getType() == int.class) {
              fields[idx].setInt(obj, 0);
          }
       }
    } catch (final IllegalAccessException ex) {
       throw new RuntimeException(ex);
    }
 }

來源

正如我在其他類似問題中提到的那樣,您可能需要考慮壓縮數據,因為默認的 java 序列化有點冗長。 為此,您可以在 Object 流和字節流之間放置一個 GZIPInput/OutputStream。

要將object 轉換為字節數組,請使用Serialization and De-serialization的概念。

教程中解釋了從 object 到字節數組的完整轉換

http://javapapers.com/core-java/java-serialization/

Q. How can we convert object into byte array?

Q. How can we serialize a object?

Q. How can we De-serialize a object?

Q. What is the need of serialization and de-serialization?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM