In this tutorial, we will see different ways to convert InputStream to String in java.

How to Convert InputStream to String:

Converting InputStream to String is a very common use case while reading data from files. In Java, there are different ways to convert InputStream to String using different libraries. Let’s look into the possibilities.

Creating a text file with sample data.

sample.txt
Robert
Joy
Chandra
Rahul

Here is a simple code which read this file and returns the data in the form of InputStream.

public static InputStream getInputStream() {
    InputStream inputstream = null;
    try {
        inputstream = new FileInputStream("sample.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return inputstream;
}

1. Convert InputStream to String – Apache IOUtils:

One of the better ways to convert InputStream to String in Java is using Apache IOUtils.

Add the below apache-commons dependency in your project’s pom.xml

pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

Reading data from sample.txt file as created above and converting InputStream to String.

public static void main(String[] args) throws Exception{
    System.out.println(inputStreamReader());
}

public static String apacheIOUtils() throws Exception{
    StringWriter writer = new StringWriter();
    IOUtils.copy(getInputStream(), writer, "UTF-8");
    return writer.toString();
}

Output:

Terminal
Robert
Joy
Chandra
Rahul

2. InputStream to String – Streams:

Reading each line from InputStream and joining each line with specific delimiter- For my case it is line break (‘\n’)

public static void main(String[] args) throws Exception{
    System.out.println(streams());
}
public static String streams(){
        String result = new BufferedReader(new InputStreamReader(getInputStream()))
                .lines().collect(Collectors.joining("\n"));
        return result;
}

Output:

Terminal
Robert
Joy
Chandra
Rahul

3. InputStream to String – ParallelStreams:

Reading each line from InputStream and joining each line with specific delimiter- For my case it is line break (‘\n’)

public static void main(String[] args) throws Exception{
    System.out.println(parallelStreams());
}

public static String parallelStreams(){
    String result = new BufferedReader(new InputStreamReader(getInputStream())).lines()
                .parallel().collect(Collectors.joining("\n"));
     return result;
}

Output:

Terminal
Robert
Joy
Chandra
Rahul

4. InputStream to String – InputStreamReader:

Reading data from InputStream, converting it into Reader and reading each byte.

public static void main(String[] args) throws Exception{
    System.out.println(inputStreamReader());
}
public static String inputStreamReader() throws Exception{
    final int bufferSize = 1024;
    final char[] buffer = new char[bufferSize];
    final StringBuilder builder = new StringBuilder();
    Reader reader = new InputStreamReader(getInputStream(), "UTF-8");
    while(true) {
        int read = reader.read(buffer, 0, buffer.length);
        if (read < 0)
            break;
        builder.append(buffer, 0, read);
    }
    return builder.toString();
}

Output:

Terminal
Robert
Joy
Chandra
Rahul

5. InputStream to String – Scanner:

Reading data from InputStream and splitting each line with specific delimiter- For my case it is line break (‘\n’)

public static void main(String[] args) throws Exception{
    System.out.println(scanner());
}
public static String scanner(){
    Scanner s = new Scanner(getInputStream()).useDelimiter("\n");
    StringBuilder builder = new StringBuilder();
    while(s.hasNext()){
        builder.append(s.nextLine()).append("\n");
    }
    return builder.toString();
}

Output:

Terminal
Robert
Joy
Chandra
Rahul

References:

Happy Learning 🙂