Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Contents Of A ByteArrayInputStream To String

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?

like image 468
Mushy Avatar asked Jun 05 '14 11:06

Mushy


People also ask

How can I get data from ByteArrayInputStream?

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.

How do I change InputStream to String?

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.

Which method is used to read a String from the input stream?

read() method reads the next byte of the data from the the input stream and returns int in the range of 0 to 255.

What is a ByteArrayInputStream?

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.


1 Answers

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); 
like image 78
Joop Eggen Avatar answered Sep 27 '22 17:09

Joop Eggen