Convert Contents Of A ByteArrayInputStream To String

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.


Addendum 2021-11-16

Since java 9 you can use the shorter readAllBytes.

byte[] bytes = in.readAllBytes();

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

Why nobody mentioned org.apache.commons.io.IOUtils?

import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

String result = IOUtils.toString(in, StandardCharsets.UTF_8);

Just one line of code.