How to convert Inputstream to String in Java
InputStream
String
io
java
InputStream to String
To convert InputStream to String, in Java, you can use BufferedReader
and InputStreamReader
classes.
Example
For this example will take a random string and put it into a InputStream object. Then the method getString will do all the work for our purpose: convert InputStream to String.
package com.admfactory.io;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class InputStreamToString {
public static void main(String[] args) {
/** Generate a InputStream object - can be read from a file. */
String str = "This is a random text message.";
InputStream is = new ByteArrayInputStream(str.getBytes());
System.out.println("Testing InputStream to String");
System.out.println();
String result = getString(is);
System.out.println(result);
System.out.println();
}
/**
* Method to convert the {@link InputStream} parameter to {@link String}
*
* @param is
* the {@link InputStream} object
* @return the {@link String} object returned
*/
public static String getString(InputStream is) {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
/** finally block to close the {@link BufferedReader} */
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
Output
Testing InputStream to String
This is a random text message.