Home > DeveloperSection > Forums > Read/convert an InputStream to a String
Goti Bandu

Total Post:119

Posted on    May-04-2015 12:00 AM

 Java Java 

 1 Reply(s)
 770  View(s)
Rate this:
If you have java.io.InputStream object, how should you process that object and produce a String?

Suppose I have an InputStream that contains text data, and I want to convert this to a String (for example, so I can write the contents of the stream to a log file).

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) { 
    // ???

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    May-04-2015 12:26 AM

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or even

// NB: does not close inputStream, you can use IOUtils.closeQuietly for that
String theString = IOUtils.toString(inputStream, encoding); 
Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers 

Taking into account file one should first get a java.io.Reader instance. This can then be read and added to a StringBuilder (we don't need StringBuffer if we are not accessing it in multiple threads, and StringBuilder is faster). The trick here is that we work in blocks, and as such don't need other buffering streams. The block size is parameterized for run-time performance optimization.

public static String slurp(final InputStream is, final int bufferSize)
  final char[] buffer = new char[bufferSize];
  final StringBuilder out = new StringBuilder();
  try (Reader in = new InputStreamReader(is, "UTF-8")) {
    for (;;) {
      int rsz = in.read(buffer, 0, buffer.length);
      if (rsz < 0)
      out.append(buffer, 0, rsz);
  catch (UnsupportedEncodingException ex) {
    /* ... */
  catch (IOException ex) {
      /* ... */
  return out.toString();

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;    
public static String readInputStreamAsString(InputStream in) 
    throws IOException {
    BufferedInputStream bis = new BufferedInputStream(in);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while(result != -1) {
      byte b = (byte)result;
      result = bis.read();
    return buf.toString();

Don't want to miss updates? Please click the below button!

Follow MindStick