问题
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
?
回答1:
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.
回答2:
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.
回答3:
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);
回答4:
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
来源:https://stackoverflow.com/questions/24059266/convert-contents-of-a-bytearrayinputstream-to-string