Read/convert an InputStream to a String

Total Post:119

 1447  View(s)
Rate this:
If you have 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) { 
    // ???
  1. Post:397

    Re: Read/convert an InputStream to a String

    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 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 =, 0, buffer.length);
          if (rsz < 0)
          out.append(buffer, 0, rsz);
      catch (UnsupportedEncodingException ex) {
        /* ... */
      catch (IOException ex) {
          /* ... */
      return out.toString();

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