
How to convert java.io.InputStream to String
While working on Files and FTP we come across some situations where we need to convert a java.io.InputStream to String. This can be easily achieved by using various techniques. Some of them are given below.This example uses Apache IOUtils which can be downloaded from http://mvnrepository.com/artifact/commons-io/commons-io/2.5
To see How to convert InputStream to String using standard Java library CLICK HERE.
Suppose we have a file in D:/sample.txt

Method 1:
File: InputStreamToStringExample.java
import java.io.*;
import org.apache.commons.io.IOUtils;
public class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("D:\\sample.txt");
String result = IOUtils.toString(inputStream, "UTF-8");
System.out.println(result);
IOUtils.closeQuietly(inputStream);
}
}
Method 2:
File: InputStreamToStringExample.java
import java.io.*;
import org.apache.commons.io.IOUtils;
public class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("D:\\sample.txt");
StringWriter stringWriter = new StringWriter();
IOUtils.copy(inputStream, stringWriter, "UTF-8");
String text = stringWriter.toString();
System.out.println(text);
}
}
Output:
This is an example.