We have different ways to convert InputStream to String as given below.
1) Using BufferedReader and InputStreamReader
Create BufferedReader object from InputStream using InputStreamReader. It will read the content line by line from BufferedReader and append the lines to StringBuilder. Once done, convert StringBuilder to String using toString
method.
import java.io.BufferedReader;
|
Output
Welcome to Java File to String |
private static String convertInputStreamToString(InputStream is) { |
3) Using ByteArrayOutputStream and BufferedInputStream
private static String convertInputStreamToString(InputStream is) { |
4) Using Scanner
private static String convertInputStreamToString(InputStream is) { |
5) Using Apache Commons IOUtils toString
private static String convertInputStreamToString(InputStream is) throws IOException {
String strResult = IOUtils.toString(is, Charset.forName("UTF-8")); return strResult; } |
6) Using Java 8 Streams
private static String convertInputStreamToString(InputStream is) throws IOException {
//Create BufferedReader from the input stream BufferedReader br = new BufferedReader(new InputStreamReader(is));
//read lines separated by new line and join them again using \n String strResult = br.lines().collect(Collectors.joining("\n"));
return null; } |