Java I/O How to - Convert InputStream to String








Question

We would like to know how to convert InputStream to String.

Answer

// ww w  .j  a va  2s.c  o  m
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main {

  public static void main(String[] args) throws Exception {
    InputStream is = Main.class.getResourceAsStream("/data.txt");
    System.out.println(convertStreamToString(is));
  }

  public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    is.close();
    return sb.toString();
  }
}

The code above generates the following result.