InputStreamString

How to Convert InputStream to String in Java

In this tutorial we are going to show three different methods that you can use in order to read a file and convert it to String in Java. The way to read a file with Java is pretty straightforward, you use an FileInputStream.

But sometimes you might want to perform several operations in that Stream, for example you might want to find several patterns using regular expressions. This kind of operation is very easy when you perform them on a String. So in this tutorial we are going to see how to read from a file with an InputStream, and then store the data in String.

There are three basic ways you can do that. Using:

So let’s write the basic code :

package inputstreamtostring;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Scanner;

public class InputStreamtoString {

    public static void main(String[] args) throws IOException {

        System.out.println(stringBuilder("/home/nikos/Desktop/input.txt"));
        System.out.println(stringWriter("/home/nikos/Desktop/input.txt"));
        System.out.println(scanner("/home/nikos/Desktop/input.txt"));

        // Date start = new Date();
        // stringBuilder("/home/nikos/Desktop/input.txt");
        // Date end = new Date();
        // System.out.println("StringBuilder time : "+(end.getTime()-start.getTime()));

        //Date start = new Date();
        //stringWriter("/home/nikos/Desktop/input.txt");
        //Date end = new Date();
        //System.out.println("StringWriter time: " + (end.getTime() - start.getTime()));

        //Date start = new Date();
        //scanner("/home/nikos/Desktop/input.txt");
        //Date end = new Date();
        //System.out.println("Scanner time: " + (end.getTime() - start.getTime()));
    }

    /**
     * read a file and converting it to String using StringBuilder
     */
    public static String stringBuilder(String fileName) throws IOException {

        StringBuilder sbuilder = null;
        FileInputStream fStream = null;
        BufferedReader input = null;

        try {

            fStream = new FileInputStream(fileName);
            input = new BufferedReader(new InputStreamReader(fStream, "UTF-8"));

            sbuilder = new StringBuilder();

            String str = input.readLine();

            while (str != null) {
                sbuilder.append(str);
                str = input.readLine();
                if (str != null) {

                    sbuilder.append("\n");

                }
            }

        } finally {
            input.close();
            fStream.close();
        }

        return sbuilder.toString();
    }

    /**
     * read a file and converting it to String using StringWriter
     */
    public static String stringWriter(String fileName) throws IOException {

        char[] buff = new char[1024];
        Writer stringWriter = new StringWriter();
        FileInputStream fStream = null;

        try {

            fStream = new FileInputStream(fileName);
            Reader bReader = new BufferedReader(new InputStreamReader(fStream, "UTF-8"));
            int n;
            while ((n = bReader.read(buff)) != -1) {
                stringWriter.write(buff, 0, n);
            }
        } finally {
            stringWriter.close();
            fStream.close();
        }
        return stringWriter.toString();
    }

    /**
     * read a file and converting it to String using Scanner
     */
    public static String scanner(String fileName) throws IOException {
        FileInputStream fStream = null;
        Scanner scanner = null;
        try {

            fStream = new FileInputStream(fileName);
            scanner = new Scanner(fStream, "UTF-8");
            return scanner.useDelimiter("\\A").next();

        } finally {
            fStream.close();
            scanner.close();
        }

    }
}

When you run the above code you will get the same output with all three methods. Now what we really want to see is how these three methods perform with a very large file. So I’m going to use input.txt which is 155.7 MB.

Go ahead and uncomment the four lines to test the StringBuilder, StringWriter and Scanner method in main():

public static void main(String[] args) throws IOException {

        //System.out.println(stringBuilder("/home/nikos/Desktop/input.txt"));
        //System.out.println(stringWriter("/home/nikos/Desktop/input.txt"));
        //System.out.println(scanner("/home/nikos/Desktop/input.txt"));

         Date start = new Date();
         stringBuilder("/home/nikos/Desktop/input.txt");
         Date end = new Date();
         System.out.println("StringBuilder time : "+(end.getTime()-start.getTime()));

        //Date start = new Date();
        //stringWriter("/home/nikos/Desktop/input.txt");
        //Date end = new Date();
        //System.out.println("StringWriter time: " + (end.getTime() - start.getTime()));

        //Date start = new Date();
        //scanner("/home/nikos/Desktop/input.txt");
        //Date end = new Date();
        //System.out.println("Scanner time: " + (end.getTime() - start.getTime()));
    }

We are going to run this in command line, because we have to use a larger heap:

$ java -Xmx2024M inputstreamtostring.InputStreamtoString 
StringBuilder time : 1276
$ java -Xmx2024M inputstreamtostring.InputStreamtoString 
StringWriter time: 876
$ java -Xmx2024M inputstreamtostring.InputStreamtoString 
Scanner time: 2212

There you go! The StringWriter method is significantly faster and that is because we are reading big chunks of the file at a time and we write them to the string. As a result, with that method we are going to make much less data transfers from Hard Drive to memory, and that’s good (even if the data size is big…). In some cases you might find that the StringBuilder method requires less heap size. So when saving memory is important consider using the StringBuilder method.

This was an Example of How to Convert InputStream to String in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button