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?
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.
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] .
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.
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..
Try ByteArrayOutputStream
. You can use write( byte[] )
and it will grow as needed.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With