skip to Main Content

How do I read / convert an InputStream into a String in Java?

To convert an InputStream into a String in Java, you can use the following steps:

  1. Create a StringBuilder object to efficiently build the string.
  2. Create a BufferedReader object, passing the InputStream wrapped in an InputStreamReader. This allows you to read the input stream line by line.
  3. Use a loop to read each line from the BufferedReader and append it to the StringBuilder object.
  4. Finally, convert the StringBuilder object to a String.

Here’s an example code snippet that demonstrates the process:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class InputStreamToStringExample {
    public static String convertInputStreamToString(InputStream inputStream) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        InputStream inputStream = ...; // Your InputStream instance

        try {
            String result = convertInputStreamToString(inputStream);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In the code above, convertInputStreamToString() is a utility method that takes an InputStream as an argument and returns the converted String. The try-with-resources statement is used to ensure proper closing of the BufferedReader after use.

Note: In this example, the InputStream is assumed to be encoded in UTF-8. If your input stream is encoded differently, you can specify the appropriate character encoding by modifying the InputStreamReader constructor parameter.

A Self Motivated Web Developer Who Loves To Play With Codes...

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top