convert
read
inputstream
java

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java, you can read or convert an InputStream into a String using various approaches. Here are some of the most common methods:

1. Using BufferedReader and InputStreamReader

This method involves wrapping the InputStream with an InputStreamReader, then wrapping that with a BufferedReader. This approach allows you to read the InputStream line by line and concatenate the result into a single String.

java
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStream;
4import java.io.InputStreamReader;
5
6public class InputStreamToStringExample {
7    public static String convertStreamToString(InputStream is) throws IOException {
8        StringBuilder sb = new StringBuilder();
9        String line;
10        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
11
12        while ((line = reader.readLine()) != null) {
13            sb.append(line).append("\n");
14        }
15
16        // Close the InputStream and BufferedReader
17        reader.close();
18
19        return sb.toString();
20    }
21}

2. Using Scanner

The Scanner class can also be used to convert an InputStream to a String. This method is more concise, but it may be slightly less efficient for large streams.

java
1import java.io.InputStream;
2import java.util.Scanner;
3
4public class InputStreamToStringExample {
5    public static String convertStreamToString(InputStream is) {
6        Scanner scanner = new Scanner(is).useDelimiter("\\A");
7        return scanner.hasNext() ? scanner.next() : "";
8    }
9}
  • useDelimiter("\\A"): This tells the Scanner to use the beginning of the input as the delimiter, effectively reading the entire input as a single string.

3. Using ByteArrayOutputStream

You can read the bytes from the InputStream and then convert them into a String using a ByteArrayOutputStream. This method is especially useful when you are dealing with binary data or want more control over character encoding.

java
1import java.io.ByteArrayOutputStream;
2import java.io.IOException;
3import java.io.InputStream;
4
5public class InputStreamToStringExample {
6    public static String convertStreamToString(InputStream is) throws IOException {
7        ByteArrayOutputStream result = new ByteArrayOutputStream();
8        byte[] buffer = new byte[1024];
9        int length;
10        while ((length = is.read(buffer)) != -1) {
11            result.write(buffer, 0, length);
12        }
13        return result.toString("UTF-8");
14    }
15}
  • toString("UTF-8"): Specifies the character encoding to use when converting the bytes to a string.

4. Using Streams (Java 8+)

If you're using Java 8 or later, you can leverage the Streams API to convert an InputStream to a String in a single line:

java
1import java.io.BufferedReader;
2import java.io.InputStream;
3import java.io.InputStreamReader;
4import java.util.stream.Collectors;
5
6public class InputStreamToStringExample {
7    public static String convertStreamToString(InputStream is) {
8        return new BufferedReader(new InputStreamReader(is))
9                .lines().collect(Collectors.joining("\n"));
10    }
11}

Summary

  • BufferedReader and InputStreamReader: Good for line-by-line reading.
  • Scanner: Concise and simple for quick conversions.
  • ByteArrayOutputStream: Offers more control, especially for binary data.
  • Java 8 Streams: Modern and elegant, best if you're working with Java 8 or newer.

Choose the method that best suits your needs based on your specific use case and the environment you're working in.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.