append part of java byte array to StringBuilder

后端 未结 3 1263
醉梦人生
醉梦人生 2021-02-18 22:01

How do I append a portion of byte array to a StringBuilder object under Java? I have a segment of a function that reads from an InputStream into a byte array. I then want to a

相关标签:
3条回答
  • 2021-02-18 22:25

    You should not use a StringBuilder for this, since this can cause encoding errors for variable-width encodings. You can use a java.io.ByteArrayOutputStream instead, and convert it to a string when all data has been read:

    byte[] buffer = new byte[4096];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream is;
    //
    //some setup code
    //
    while (is.available() > 0) {
       int len = is.read(buffer);
       out.write(buffer, 0, len);
    }
    String result = out.toString("UTF-8"); // for instance
    

    If the encoding is known not to contain multi-byte sequences (you are working with ASCII data, for instance), then using a StringBuilder will work.

    0 讨论(0)
  • 2021-02-18 22:26

    You could just create a String out of your buffer:

    String s = new String(buffer, 0, len);

    Then if you need to you can just append it to a StringBuilder.

    0 讨论(0)
  • 2021-02-18 22:41

    Something like below should do the trick for you.

    byte[] buffer = new byte[3];
    buffer[0] = 'a';
    buffer[1] = 'b';
    buffer[2] = 'c';
    StringBuilder sb = new StringBuilder(new String(buffer,0,buffer.length-1));
    System.out.println("buffer has:"+sb.toString()); //prints ab
    
    0 讨论(0)
提交回复
热议问题