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.
Depending on what licenses you are comfortable with, it's a one liner with Jakarta-Commons IO library.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With