Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java mutable byte array data structure

Tags:

java

I'm trying to find an easy way to create a mutable byte array that can automatically append any primitive Java data type. I've been searching but could not find anything useful.

I'm looking for something like this

ByteAppender byteStructure = new ByteAppender();
byteStructure.appendInt(5);
byteStructure.appendDouble(10.0);

byte[] bytes = byteStructure.toByteArray();

There is ByteByffer which is great, but you have to know the size of the buffer before you start, which won't work in my case. There is a similar thing (StringBuilder) for creating Strings, but I cannot find one for Bytes.

I thought this would be obvious in Java.

like image 752
Jason Avatar asked Jan 17 '14 01:01

Jason


1 Answers

I guess you are looking for java.io.DataOutputStream

ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(1234);
dout.writeLong(123L);
dout.writeFloat(1.2f);
byte[] storingData = out.toByteArray();

How to use storingData?

//how to use storingData?
ByteArrayInputStream in = new ByteArrayInputStream(storingData);
DataInputStream din = new DataInputStream(in);
int v1 = din.readInt();//1234
long v2 = din.readLong();//123L
float v3 = din.readFloat();//1.2f
like image 57
BlackJoker Avatar answered Nov 01 '22 00:11

BlackJoker