How to convert a Java object into a byte array?

To convert a Java object to a byte array, you can use Java’s serialization and deserialization mechanisms. Here is an example code that converts a Java object named “obj” to a byte array:

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

public class ObjectToByteArray {
    public static byte[] convertToByteArray(Object obj) throws IOException {
        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
        ObjectOutputStream objOutStream = new ObjectOutputStream(byteOutStream);
        objOutStream.writeObject(obj);
        objOutStream.flush();
        byte[] byteArray = byteOutStream.toByteArray();
        byteOutStream.close();
        objOutStream.close();
        return byteArray;
    }

    public static void main(String[] args) {
        try {
            // 创建一个示例对象
            MyClass obj = new MyClass("Hello World");

            // 将对象转换为byte数组
            byte[] byteArray = convertToByteArray(obj);

            // 打印byte数组
            for (byte b : byteArray) {
                System.out.print(b + " ");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class MyClass implements java.io.Serializable {
    private String message;

    public MyClass(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

In the code example above, the convertToByteArray method converts a Java object to a byte array. Firstly, create a ByteArrayOutputStream object and an ObjectOutputStream object to serialize the object into a byte stream. Then, call the writeObject method to write the object into the byte stream, and use the toByteArray method to convert the byte stream into a byte array. Finally, close the stream and return the byte array.

In the main method, we created an instance object of MyClass and called the convertToByteArray method to convert it into a byte array. Finally, we printed the byte array using a loop.

Please note that in order to convert a Java object to a byte array, the object must implement the Serializable interface.

bannerAds