As we discussed earlier about Java I/O in Decorator Design Pattern. Java I/O  often results in a large number of small classes that can be overwhelmed to developer trying to use the API. In this article we are going to see 11 ways to convert Java InputStream to String.

Let’s take an practical example, I am going to pass a file as InputStream and convert to as String and you can use any InputStream in your case. The file contains following text in it and so every solution on execution will give same text as output.

------------------
System Information
------------------
      Time of this report: 3/28/2019, 12:40:25
             Machine name: LAPTOP-DDDAAANN
               Machine Id: {8H4F7E8A-671V-BSHS-UDHH-MJSHHGSJSK}
         Operating System: Windows 10 Home 64-bit (10.0, Build 17134) (17134.rs4_release.180410-1804)
                 Language: English (Regional Setting: English)
      System Manufacturer: SOME COMPANY
             System Model: SOME MODEL
                     BIOS: 5NSJSJS (type: UEFI)
                Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (8 CPUs), ~2.8GHz
                   Memory: 16384MB RAM
      Available OS Memory: 16276MB RAM
                Page File: 6212MB used, 12495MB available
              Windows Dir: C:\WINDOWS
          DirectX Version: DirectX 12
      DX Setup Parameters: Not found
         User DPI Setting: 120 DPI (125 percent)
       System DPI Setting: 120 DPI (125 percent)
          DWM DPI Scaling: UnKnown
                 Miracast: Available, with HDCP
Microsoft Graphics Hybrid: Supported
           DxDiag Version: 10.00.17134.0001 64bit Unicode

Way to Convert Java InputStream to String

1. Using Scanner (JDK)

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

//Using Scanner (JDK)
public class Example1 {

  public static void main(String[] args) {
    try {
      FileInputStream fileInputStream = new FileInputStream("DxDiag.txt");
      Scanner s = new Scanner(fileInputStream).useDelimiter("\\A");
      String result = s.hasNext() ? s.next() : "";
      System.out.println(result);
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

2. Using IOUtils.toString (Apache Utils)

import java.io.FileInputStream;

import org.apache.commons.io.IOUtils;

//Using IOUtils.toString (Apache Utils)
public class Example2 {

  public static void main(String[] args) {
    FileInputStream fileInputStream;
    try {
      fileInputStream = new FileInputStream("DxDiag.txt");
      String result = IOUtils.toString(fileInputStream);
      System.out.println(result);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

3. Using CharStreams (Guava)

import java.io.FileInputStream;
import java.io.InputStreamReader;
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;

public class Example3 {

  public static void main(String[] args) {

    FileInputStream fileInputStream;
    try {
      fileInputStream = new FileInputStream("DxDiag.txt");
      String result = CharStreams.toString(new InputStreamReader(fileInputStream, Charsets.UTF_8));
      System.out.println(result);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

4. Using Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class Example4 {

  public static void main(String[] args) {

    FileInputStream fileInputStream;
    try {
      fileInputStream = new FileInputStream("DxDiag.txt");
      String result = new BufferedReader(new InputStreamReader(fileInputStream))
            .lines().collect(Collectors.joining("\n"));
      System.out.println(result);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

5. Using parallel Stream API (Java 8). Warning: This solution converts different line breaks (like \r\n) to \n.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class Example5 {
  public static void main(String[] args) {

    FileInputStream fileInputStream;
    try {
      fileInputStream = new FileInputStream("DxDiag.txt");
      String result = new BufferedReader(new InputStreamReader(fileInputStream)).lines().parallel()
          .collect(Collectors.joining("\n"));
      System.out.println(result);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

6. Using InputStreamReader and StringBuilder (JDK)

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class Example6 {

  public static void main(String[] args) {

    FileInputStream fileInputStream;
    try {
      fileInputStream = new FileInputStream("DxDiag.txt");
      final int bufferSize = 1024;
      final char[] buffer = new char[bufferSize];
      final StringBuilder out = new StringBuilder();
      Reader in = new InputStreamReader(fileInputStream, "UTF-8");
      for (; ; ) {
          int rsz = in.read(buffer, 0, buffer.length);
          if (rsz < 0)
              break;
          out.append(buffer, 0, rsz);
      }
      System.out.println(out.toString());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

7. Using StringWriter and IOUtils.copy (Apache Commons)

import java.io.FileInputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;

public class Example7 {

  public static void main(String[] args) {

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream("DxDiag.txt");
      StringWriter writer = new StringWriter();
      IOUtils.copy(inputStream, writer, "UTF-8");
      System.out.println(writer.toString());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

8. Using ByteArrayOutputStream and inputStream.read (JDK)

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class Example8 {

  public static void main(String[] args) {

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream("DxDiag.txt");
      ByteArrayOutputStream result = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int length;
      while ((length = inputStream.read(buffer)) != -1) {
          result.write(buffer, 0, length);
      }
      // StandardCharsets.UTF_8.name() > JDK 7
      System.out.println(result.toString("UTF-8"));
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

9. Using BufferedReader (JDK). Warning: This solution converts different line breaks (like \n\r) to line.separator system property (for example, in Windows to “\r\n”).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Example9 {

  public static void main(String[] args) {

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream("DxDiag.txt");
      String newLine = System.getProperty("line.separator");
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      StringBuilder result = new StringBuilder();
      boolean flag = false;
      for (String line; (line = reader.readLine()) != null; ) {
          result.append(flag? newLine: "").append(line);
          flag = true;
      }
      System.out.println(result.toString());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

10. Using BufferedInputStream and ByteArrayOutputStream (JDK)

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class Example10 {

  public static void main(String[] args) {

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream("DxDiag.txt");
      BufferedInputStream bis = new BufferedInputStream(inputStream);
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      int result = bis.read();
      while(result != -1) {
          buf.write((byte) result);
          result = bis.read();
      }
      // StandardCharsets.UTF_8.name() > JDK 7
      System.out.println(buf.toString("UTF-8"));
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

11. Using inputStream.read() and StringBuilder (JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class Example10 {

  public static void main(String[] args) {

    FileInputStream inputStream;
    try {
      inputStream = new FileInputStream("DxDiag.txt");
      BufferedInputStream bis = new BufferedInputStream(inputStream);
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      int result = bis.read();
      while(result != -1) {
          buf.write((byte) result);
          result = bis.read();
      }
      // StandardCharsets.UTF_8.name() > JDK 7
      System.out.println(buf.toString("UTF-8"));
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Warning:

  1. Solutions 4, 5 and 9 convert different line breaks to one.
  2. Solution 11 can’t work correctly with Unicode text

Apart from above solutions, we might also have our method of implementation to convert Java InputStream to String. Please comment your own findings below to get more solutions to the list.

Performance Result

Performance tests for big String (length = 50100), (mode = Average Time, system = Linux, score 200,715 is the best):

Solution 8 performs faster among other solutions !!!!

Benchmark                        Mode  Cnt   Score        Error  Units
 8. ByteArrayOutputStream and read (JDK)        avgt   10   200,715 ±   18,103  us/op
 1. IOUtils.toString (Apache Utils)             avgt   10   300,019 ±    8,751  us/op
 6. InputStreamReader and StringBuilder (JDK)   avgt   10   347,616 ±  130,348  us/op
 7. StringWriter and IOUtils.copy (Apache)      avgt   10   352,791 ±  105,337  us/op
 2. CharStreams (guava)                         avgt   10   420,137 ±   59,877  us/op
 9. BufferedReader (JDK)                        avgt   10   632,028 ±   17,002  us/op
 5. parallel Stream Api (Java 8)                avgt   10   662,999 ±   46,199  us/op
 4. Stream Api (Java 8)                         avgt   10   701,269 ±   82,296  us/op
10. BufferedInputStream, ByteArrayOutputStream  avgt   10   740,837 ±    5,613  us/op
 3. Scanner (JDK)                               avgt   10   751,417 ±   62,026  us/op
11. InputStream.read() and StringBuilder (JDK)  avgt   10  2919,350 ± 1101,942  us/op

Know more about following,

java.io.BufferedReader

java.util.Scanner

Collectors –  implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

Apache Commons IO – provides the utility class org.apache.commons.io.IOUtils to convert an InputStream.

Google Guava – provides also a powerful way to easily convert an inputStream to a String Java object.

Conclusion

Check the best way to do the simple conversion – InputStream to String – in a correct and readable way – Analyze your case with above solutions and choose the best one to implement.

Please follow and like us: