Write a Java Program to Convert InputStream to String

Converting an InputStream to a String is a common task in Java programming.

This is useful when reading data from a file or network connection, and you want to store it as a String object.

In this tutorial, we will show you how to convert an InputStream to a String using Java.


First, we need to create an InputStream object.

For example, we can create an InputStream object from a file as follows:

InputStream inputStream = new FileInputStream("input.txt");

Next, we need to convert this InputStream object to a String.

One way to do this is to use a BufferedReader object to read the data from the InputStream and append it to a StringBuilder object.

Here’s how we can do this:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    stringBuilder.append(line);
}
String result = stringBuilder.toString();

In the above code, we created a BufferedReader object using the InputStreamReader class to read the data from the InputStream.

We then created a StringBuilder object to store the data as a String.

Finally, we used a while loop to read each line from the BufferedReader and append it to the StringBuilder object.

Once we have read all the data from the InputStream, we can convert the StringBuilder object to a String using the toString() method.

String result = stringBuilder.toString();

The result variable now contains the contents of the InputStream as a String object.


In summary, converting an InputStream to a String in Java involves creating an InputStream object, using a BufferedReader object to read the data from the InputStream, appending the data to a StringBuilder object, and finally converting the StringBuilder object to a String using the toString() method.