Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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) {      // ??? } 
like image 721
Daniel Fortunov Avatar asked Nov 19 '09 14:11

Daniel Fortunov


People also ask

How do you write InputStream to console?

BufferedInputStream bin = new BufferedInputStream(in); int b; while ( ( b = bin. read() ) != -1 ) { char c = (char)b; System.


2 Answers

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.

like image 80
teabot Avatar answered Sep 21 '22 07:09

teabot


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 } 
like image 23
ZZ Coder Avatar answered Sep 22 '22 07:09

ZZ Coder