9

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?

Community
  • 1
  • 1
Baz
  • 10,775
  • 30
  • 121
  • 236

2 Answers2

5

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.

Joachim Sauer
  • 278,207
  • 54
  • 523
  • 586
2

Here is a link to several ways to do it (with and without external libraries). A way to do it (extracted from the above link) is using a Java Scanner (since Java 5):

public class InputStreamTest {

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);
    }
}
acostache
  • 2,125
  • 6
  • 22
  • 48
  • 1
    Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Joachim Sauer Dec 05 '12 at 12:18
  • Yes, you are correct - i have improved the answer just now. – acostache Dec 05 '12 at 12:45