Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte array of unknown length in java

Tags:

java

byte

buffer

I am constructing an array of bytes in java and I don't know how long the array will be.

I want some tool like Java's StringBuffer that you can just call .append(byte b) or .append(byte[] buf) and have it buffer all my bytes and return to me a byte array when I'm done. Is there a class that does for bytes what StringBuffer does for Strings? It does not look like the ByteBuffer class is what I'm looking for.

Anyone have a good solution?

like image 685
jbu Avatar asked Mar 19 '09 23:03

jbu


People also ask

How to write byte array in Java?

byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 }; String str = new String(byteArray1, 0, 3, StandardCharsets. UTF_8); Above code is perfectly fine and 'str' value will be 'PAN'. That's all about converting byte array to String in Java.

How to declare empty byte array in Java?

In general Java terminology, an empty byte array is a byte array with length zero, and can be created with the Java expression new byte[0] .

How to check if byte array is empty in Java?

Empty Array in Java An array is empty only when it contains zero(0) elements and has zero length. We can test it by using the length property of the array object.

What is ByteArray Java?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..


2 Answers

Try ByteArrayOutputStream. You can use write( byte[] ) and it will grow as needed.

like image 167
Clint Avatar answered Oct 12 '22 13:10

Clint


Just to extend the previous answer, you can use ByteArrayOutputStream and it's method public void write(byte[] b, int off, int len), where parameters are:

b - the data

off - the start offset in the data

len - the number of bytes to write

If you want to use it as a "byte builder" and insert byte by byte, you can use this:

byte byteToInsert = 100; ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(new byte[]{byteToInsert}, 0, 1); 

Then you can use baos.toString() method to convert the array to string. The advantage is when you need to set up encoding of input, you can simply use i.e.:

baos.toString("Windows-1250") 
like image 30
Micer Avatar answered Oct 12 '22 13:10

Micer