Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append InputStream object to String object [duplicate]

Tags:

java

Possible Duplicate:
Read/convert an InputStream to a String

I'm trying to append data from a InputStream object to a string as follows:

byte[] buffer = new byte[8192];
InputStream stdout;
String s = "";      
while(IsMoreInputDataAvailable()) {
    int length = this.stdout.read(buffer);
    s += new String(this.buffer, 0, length, "ASCII");

Is there an easier way of doing this without using Apache or such libraries?

like image 756
Baz Avatar asked Dec 05 '12 12:12

Baz


1 Answers

The usual way to read character data from an InputStream is to wrap it in a Reader. InputStreams are for binary data, Readers are for character data. The appropriate Reader to read from an InputStream is the aptly named InputStreamReader:

Reader r = new InputStreamReader(stdout, "ASCII");
char buf = new char[4096];
int length;
StringBuilder s = new StringBuilder();
while ((length = r.read(buf)) != -1) {
    s.append(buf, 0, length);
}
String str = s.toString();

Note that appending to a String repeatedly inside a loop is usually a bad idea (because each time you'll need to copy the whole string), so I'm using a StringBuilder here instead.

like image 98
Joachim Sauer Avatar answered Nov 09 '22 01:11

Joachim Sauer