Convert Contents Of A ByteArrayInputStream To String

强颜欢笑 提交于 2019-12-03 09:41:53

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.

Cherry

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.

Use Scanner and pass to it's constructor the ByteArrayInputStream then read the data from your Scanner , check this example :

ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(new byte[] { 65, 80 });
Scanner scanner = new Scanner(arrayInputStream);
scanner.useDelimiter("\\Z");//To read all scanner content in one String
String data = "";
if (scanner.hasNext())
    data = scanner.next();
System.out.println(data);

Use Base64 encoding

Assuming you got your ByteArrayOutputStream :

ByteArrayOutputStream baos =...
String s = new String(Base64.Encoder.encode(baos.toByteArray()));

See http://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!