ENGLISH

JAVA object to byte array conversion method

개미v 2021. 1. 30. 17:07

How to convert an object to byte array in JAVA.

The easiest way to convert an object to byte array is to use the Object Serialization ObjectOutputStream.
However, there is a problem that object serialization is compatible only with Java.
Object serialization cannot be used for socket communication with heterogeneous (c language, .NET, etc.).

So the method I found is to use ByteArrayOutputStream.

Below is an example of converting a class object configured with 16 bytes to byte[].
To implement it in a functional form for general use, it would be necessary to use the concept of Java reflection.

 

public class ProtocolDto {
	public byte sender;
	public byte receiver;
	public short cmd;
	public short error;
	public short warning;
	public int reserved;
	public int data_length;
}

 

ProtocolDto protocolDto = new ProtocolDto();

// Object to Byte[] 변환
byte[] dtoByteArray = null;

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
try {
	dataOutputStream.writeByte(protocolDto.sender);
	dataOutputStream.writeByte(protocolDto.receiver);
	dataOutputStream.writeShort(protocolDto.cmd);
	dataOutputStream.writeShort(protocolDto.error);
	dataOutputStream.writeShort(protocolDto.warning);
	dataOutputStream.writeInt(protocolDto.reserved);
	dataOutputStream.writeInt(protocolDto.data_length);
	dataOutputStream.flush();
	dtoByteArray = byteArrayOutputStream.toByteArray();
} finally {
	dataOutputStream.close();
	byteArrayOutputStream.close();
}

// Result 16bytes
System.out.println(dtoByteArray.length);