Byte array of unknown length in java

前端 未结 4 1122
执笔经年
执笔经年 2020-12-23 19:13

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

4条回答
  •  臣服心动
    2020-12-23 19:22

    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")
    

提交回复
热议问题