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
?
Example: ByteArrayInputStream to read data ByteArrayInputStream input = new ByteArrayInputStream(array); Here, the input stream includes all the data from the specified array. To read data from the input stream, we have used the read() method.
To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.
read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255.
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. Closing a ByteArrayInputStream has no effect.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With