Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read text from InputStream [duplicate]

Tags:

java

If I start with a java.io.InputStream, what's the easiest way to read the entire stream out into a String (assuming utf-8)?

This should be pretty easy but I'm mostly a C# person and google is failing me on this. Thanks.

like image 631
jthg Avatar asked Dec 11 '09 23:12

jthg


2 Answers

Depending on what licenses you are comfortable with, it's a one liner with Jakarta-Commons IO library.

like image 121
zznate Avatar answered Oct 01 '22 14:10

zznate


Do specify the character encoding. Do not waste code, introduce bugs, and slow execution with a BufferedReader.

Here is an example. You could parameterize it with a buffer size, encoding, etc.

static String readString(InputStream is) throws IOException {   char[] buf = new char[2048];   Reader r = new InputStreamReader(is, "UTF-8");   StringBuilder s = new StringBuilder();   while (true) {     int n = r.read(buf);     if (n < 0)       break;     s.append(buf, 0, n);   }   return s.toString(); } 
like image 26
erickson Avatar answered Oct 01 '22 14:10

erickson