Tutorial :How do I convert an InputStream to a String in Java?


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) {       // ???  }  


This is my version,

public static String readString(InputStream inputStream) throws IOException {        ByteArrayOutputStream into = new ByteArrayOutputStream();      byte[] buf = new byte[4096];      for (int n; 0 < (n = inputStream.read(buf));) {          into.write(buf, 0, n);      }      into.close();      return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding  }  


If you want to do it simply and reliably, I suggest using the Apache Jakarta Commons IO library IOUtils.toString(java.io.InputStream, java.lang.String) method.


String text = new Scanner( inputStream).useDelimiter("\\A").next();  

more here


You can use a BufferedReader to read the stream into a StringBuilder in a loop, and then get the full contents from the StringBuilder:

public String convertStreamToString(InputStream is) {     BufferedReader reader = new BufferedReader(new InputStreamReader(is));     StringBuilder sb = new StringBuilder();       String line = null;       try {       while ((line = reader.readLine()) != null) {       sb.append(line + "\n");       }     } catch (IOException e) {       e.printStackTrace();     } finally {       try {         is.close();       } catch (IOException e) {         e.printStackTrace();       }     }      return sb.toString();   }   

Full disclosure: This is a solution I found on KodeJava.org. I am posting it here for comments and critique.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »