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 stre
Below code might help you.
public String convertBytestoString(InputStream inputStream)
{
int bytes;
byte[] buffer = new byte[1024];
bytes = inputStream.read(buffer);
String stringData = new String(buffer,0,bytes);
return stringData;
}
String text = new Scanner(inputStream).useDelimiter("\\A").next();
The only tricky is to remember the regex
\A
, which matches the beginning of input. This effectively tellsScanner
to tokenize the entire stream, from beginning to (illogical) next beginning...
- from the Oracle Blog
With Java 9+ even shorter:
static String readString(InputStream inputStream) throws IOException {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // Or whatever encoding
}
Note: InputStream is not closed in this example.
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.
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.