Convert Contents Of A ByteArrayInputStream To String

Mushy picture Mushy · Jun 5, 2014 · Viewed 75.9k times · Source

I read this post but I am not following. I have seen this but have not seen a proper example of converting a ByteArrayInputStream to String using a ByteArrayOutputStream.

To retrieve the contents of a ByteArrayInputStream as a String, is using a ByteArrayOutputstream recommended or is there a more preferable way?

I was considering this example and extend ByteArrayInputStream and utilize a Decorator to increase functionality at run time. Any interest in this being a better solution to employing a ByteArrayOutputStream?

Answer

Joop Eggen picture Joop Eggen · Jun 5, 2014

A ByteArrayOutputStream can read from any InputStream and at the end yield a byte[].

However with a ByteArrayInputStream it is simpler:

int n = in.available();
byte[] bytes = new byte[n];
in.read(bytes, 0, n);
String s = new String(bytes, StandardCharsets.UTF_8); // Or any encoding.

For a ByteArrayInputStream available() yields the total number of bytes.


Answer to comment: using ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
for (;;) {
    int nread = in.read(buf, 0, buf.length);
    if (nread <= 0) {
        break;
    }
    baos.write(buf, 0, nread);
}
in.close();
baos.close();
byte[] bytes = baos.toByteArray();

Here in may be any InputStream.


Since java 10 there also is a ByteArrayOutputStream#toString(Charset).

String s = baos.toString(StandardCharsets.UTF_8);