Reading an InputStream to a String

By Paulus, 4 December, 2010
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null)
{
     sb.append(line);
}
br.close();
result = sb.toString();
System.out.println(result);
  1. Get an Input Stream from an existing object such as a connection object and pass it as the parameter in the constructor of the InputStreamReader
  2. Create a new BufferedReader object and pass the newly created InputStreamReader throught the constructor.
  3. Create a StringBuffer object for later use.
  4. Iterate through the BufferedReader, reading each line of data. Append the data into the StringBuffer object.
  5. When done close the BufferedReader object.
  6. Convert the StringBuffer to a string and print it.