How to read data from InputStream into String in java

This is very common requirement in several type of applications where you have you read data from network stream or from file system and do some operation on it. If you are using java.nio package then for reading a file, you can read some effective ways my post: 3 ways to read files in java NIO. But, if you are still working on old java IO classes or you are open to work on any new effective way of reading files into string, you are in right place.

io-read-into-string

Sections in this post:

Most common way using BufferedReader
Using apache commons IOUtils
Using java.util.Scanner

1) Most common way using BufferedReader (Basic)

You must have seen this code lots of time. Use it directly when you need it.

package com.howtodoinjava.demo.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadStreamIntoStringUsingReader
{
	public static void main(String[] args) throws FileNotFoundException, IOException 
	{
		InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	    StringBuilder out = new StringBuilder();
	    String line;
	    while ((line = reader.readLine()) != null) {
	        out.append(line);
	    }
	    System.out.println(out.toString());   //Prints the string content read from input stream
	    reader.close();
	}
}

2) Using apache commons IOUtils (Most readable)

Apache commons has a very classy facility for this purpose which makes code a lot cleaner and easy to read. It’s fast too.

package com.howtodoinjava.demo.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;

public class ReadStreamIntoStringUsingIOUtils
{
	public static void main(String[] args) throws FileNotFoundException, IOException 
	{
		//Method 1 IOUtils.copy()
		
		StringWriter writer = new StringWriter();
		IOUtils.copy(new FileInputStream(new File("C:/temp/test.txt")), writer, "UTF-8");
		String theString = writer.toString();
		System.out.println(theString);
		
		//Method 2 IOUtils.toString()
		
		String theString2 = IOUtils.toString(new FileInputStream(new File("C:/temp/test.txt")), "UTF-8");
		System.out.println(theString2);
	}
}

3) Using java.util.Scanner (Most tricky)

This is something new. The reason it works is because Scanner iterates over tokens in the stream, and in this case we separate tokens using “beginning of the input boundary” (A) thus giving us only one token for the entire contents of the stream.

package com.howtodoinjava.demo.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadStreamIntoStringUsingScanner
{
	@SuppressWarnings("resource")
	public static void main(String[] args) throws FileNotFoundException, IOException 
	{
		FileInputStream fin = new FileInputStream(new File("C:/temp/test.txt"));
		java.util.Scanner scanner = new java.util.Scanner(fin,"UTF-8").useDelimiter("\A");
		String theString = scanner.hasNext() ? scanner.next() : "";
		System.out.println(theString);
		scanner.close();
	}
}

That’s all. The purpose of this post is to provide quick links for the very specific purpose i.e. to read input stream into string.

Happy Learning !!

4 thoughts on “How to read data from InputStream into String in java”

  1. please you can explain me the following line of code?

    java.util.Scanner scanner = new java.util.Scanner(fin,”UTF-8″).useDelimiter(“A”);
    String theString = scanner.hasNext() ? scanner.next() : “”;

    What it is the delimiter”A”
    and what it is a caracter of escape?
    Tank you very much
    mauro

  2. Is it good to test the performance of scanner ? . If yes, then compare to most common way method. This scanner takes much time to read the file. If i am wrong please correct. Your resources are so helpful

    long startTime = Calendar.getInstance().getTimeInMillis();
    FileInputStream fin = new FileInputStream(new File(“/Users/administrator/Desktop/code.txt”));
    java.util.Scanner scanner = new java.util.Scanner(fin,”UTF-8″).useDelimiter(“\A”);
    String theString = scanner.hasNext() ? scanner.next() : “”;
    scanner.close();
    System.out.println(“Scanner performance ” + (Calendar.getInstance().getTimeInMillis() – startTime));

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *


nine − = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>