Wednesday, August 4, 2021

5 ways to convert InputStream to String in Java - Example Tutorial

InputStream to String Conversion Example
Converting InputStream to String in Java has become very easy after the introduction of Scanner class in Java 5 and due to the development of several open-source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in a log file or want to operate on whole String.

Before Java 5 you would have to write lots of boilerplate code to read String line by line or byte by byte depending upon whether you are using either BufferedReader or not but as I said since JDK 5 added Scanner for reading input, its fairly easy to convert InputStream into String.

Before Converting any InputStream or ByteStream into String don't forget to provide character encoding or charset which tells Java Which characters to expect from those streams of bytes. in the absence of correct character encoding, you might alter the output because the same bytes can be used to represent different characters in a different encoding. 

Another thing to keep in mind is that if you don't provide character encoding, Default character encoding in Java will be used which can be specified from System property "file.encoding" or "UTF-8" if file.encoding is not specified. In this Java tutorial, we will see 5 different examples of converting InputStream to String in Java both by using standard JDK libraries and using open source libraries.


How to convert InputStream to String in Java – 5 Examples

here are different ways to convert InputStream to String in Java, first we will see the most simple way of reading InputStream as String.



1. InputStream to String -  Using Java 5 Scanner

Convert InputStream to String in Java - 5 Example tutorialjava.util.Scanner has constructor which accept an InputStream, a character encoding and a delimiter to read String from InputStream. Here we have used delimiter as "\A" which is a boundary match for the beginning of the input as declared in java.util.regex.Pattern and that's why Scanner is returning whole String form InputStream

I frequently use this technique to read input from users in Java using System.in which is most common example of InputStream in Java, but as demonstrated here this can also be used to read text file in Java.

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

/**
 * Java program example to demonstrate How to convert InputStream into String by using JDK
 * Scanner utility. This program will work Java 5 onwards as Scanner was added in Java 5.
 */
       
public class InputStreamTest {

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);
    }
}

Output:
This String is read from InputStream by changing InputStream to String in Java.

If you want to see how an incorrect character encoding completely changes the String just change the character encoding form "UTF-8" to "UTF-16" and you see Chinese(maybe) characters instead of English.

Output:
?????????????!???????????!??????^(4)????????


2. Convert InputStream to String - Plain old JDK4 Example

If you still need to do it on plain old Java on JDK4 without including any additional dependency in your PATH and Classpath then here is a quick example using BufferedReader in Java.

Remember you can also do this by reading byte by byte from InputStream but that's very slow so consider using BufferedReader for better performance even if you code on JDK4. For more performance tips see my post 4 JDBC performance tips in Java program. Let’s see an example of converting InputStream to String using BufferedReader in Java.

/**
 * Java program to demonstrate How to read InputStream as String
 * using BufferedReader and StringBuilder in Java.
 * This is old and standard way of converting an InputStream into String in Java
 */

public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        String line = bufferedReader.readLine();
        while(line != null){
            inputStringBuilder.append(line);inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        System.out.println(inputStringBuilder.toString());

}
Output:
This String is read from InputStream by changing InputStream to String in Java.
second line


This is a good plain old Java method of converting InputStream to String without adding any extra dependency but remember it's converting \r to \n because we are reading line by line, which in most cases is fine.


3. Read InputStream to String - Using Apache IOUtils library

As I said earlier there are many open-source libraries in Java which makes coding lot easier than any other language. Here is a code example for How to convert InputStream to String in Java using Apache IOUtils

/**
 * Example of How to read InputStream into String by using Apache IOUtils library.
 * Nice and clean way of getting InputStream as String in Java
 */


FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);

Isn't it a compact way of converting InputStream to String in Java, just one line of code and that does take care of character encoding as well?



4. InputStream to String - Using Google's guava-libraries

Google has open-sourced its own set of Java libraries they use for Java development inside Google. it has lots of utility functions and also complements Apache commons package. Here is a quick way of converting InputStream to String using Google libraries:

String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));

Regarding dependency, You need to include the guava library i.e. guava-11.0.1.jar in your project classpath. here is a full code example:

import com.google.common.io.CharStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * How to convert InputStream into String in Java using Google's Guava library
 */

public class InputStreamToString{

    public static void main(String args[]) throws UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
        System.out.println(stringFromStream);
    }    
}



5. How to read InputStream into String with IOUtils.copy and StringWriter class

java.io.StringWriter is another convenient way of reading writing Strings and by using IOUtils.copy() you can copy contents from InputStream to the reader, Here is a complete code example of reading InputStream as String using StringWriter:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;

/**
  * Java Program to demonstrate reading of InputStream as String
  * using StringWriter and Apache IOUtils
  */

public class InputStreamToStringConversion{

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringWriter writer = new StringWriter();
        String encoding = "UTF-8";
        IOUtils.copy(fis, writer, encoding);
        System.out.println(writer.toString());
    }
}

That's all on converting InputStream to String in Java by using standard core java library and by using open source Apache commons IOUtils and Google's guava libraries. Don't forget Character encoding when converting bytes to String which is the case here also make a convenient choice as sometimes adding an additional library for one functionality is not the best option. let us know if you know any other way of converting InputStream to String in Java.


Related Java tutorials and Examples

8 comments :

Anonymous said...

Don't forget to be sure the whole stream FITS nicely in memory. There's usually a reason things are a stream!

Anonymous said...

Using Java 7:
java.nio.file.Files#readAllLines

see:
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29

Mikhail B said...

concerning guava-11.0.1 way: CharStreams.toString(new InputStreamReader(fis, "UTF-8")) does not close the input stream after, can't be an issue?

Anonymous said...

is this work for other file formats like .rar,.exe and mutimedia file format ?

Anonymous said...

I think Java solution work for all kind of files including text and binary, but just remember to provide correct character encoding while reading data from stream, otherwise your code will use default character stream of platform, which may not be the same as of contents you are reading. Another thing, don't forget to close streams and files once you read data from them. This will release file descriptor associated with them.

Anonymous said...

IOUtils.toString() doesn't close the input stream, so you can't really
write one-liners.

Anonymous said...

How about a method that return FileInputStream content to another class

javin paul said...

Hello @Anonymous, can you elaborate on this? Any usecase?

Post a Comment