Java InputStream to String

Learn to convert an InputStream to a String using BufferedReader, Scanner or IOUtils classes. Reading a String from InputStream is very common requirement in several type of applications where we have to read the data from network stream or from file system to do some operation on it.

Table of Contents

1. InputStream to String using Guava
2. BufferedReader
3. IOUtils
4. java.util.Scanner

1. InputStream to String using Google Guava IO

Guava library has some very useful classes and methods to perform IO operations. These classes hide all complexities, otherwise exposed.

1.1. Dependencies

Maven dependency for Google Guava.

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>26.0-jre</version>
</dependency>

1.2. ByteSource class

ByteSource represents a readable source of bytes, such as a file. It has utility methods that are typically implemented by opening a stream, doing something and finally closing the stream that was opened.

Its asCharSource(charset) method decodes the bytes read from a source as characters in the given Charset. It returns the characters as String as the method output.

Example 1: Java program to convert InputStream to String

package com.howtodoinjava.demo;

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

import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;

public class Main 
{
    public static void main(String[] args) throws Exception
    {
        InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));

        ByteSource byteSource = new ByteSource() {
            @Override
            public InputStream openStream() throws IOException {
                return inputStream;
            }
        };
     
        String text = byteSource.asCharSource(Charsets.UTF_8).read();
        
        System.out.println(text);
    }
}

1.2. CharStreams

The CharStreams class also provides utility methods for working with character streams. Using InputStreamReader along with CharStreams helps in converting an InputStream to a String.

Example 2: Converting an InputStream to a String with InputStreamReader

Java program to convert InputStream to String with CharStreams class in Google guava library.

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

import com.google.common.io.CharStreams;

public class Main 
{
    public static void main(String[] args) throws Exception
    {
        InputStream inputStream = new FileInputStream(new File("C:/temp/test.txt"));

        String text = null;

        try (final Reader reader = new InputStreamReader(inputStream)) {
            text = CharStreams.toString(reader);
        }
        
        System.out.println(text);
    }
}

2. InputStream to String with BufferedReader

Using BufferedReader is most easy and popular way to read a file into String. It helps to read the file as inputstream and process it line by line.

Example 3: How to convert an InputStream to a string in Java

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();
	}
}

3. IOUtils – Apache Commons IO

Apache commons has a very useful class IOUtils to read file content into String. It makes code a lot cleaner and easy to read. It provide a better performance too.

Use either of the two methods-

  1. IOUtils.copy()
  2. IOUtils.toString()

Example 4: Reading FileInputStream to String

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);
	}
}

4. Java InputStream to String using Scanner

Using Scanner class is not so popular, but it works. The reason it works is because Scanner iterates over tokens in the stream, and in this process, we can separate tokens using the “beginning of the input boundary” thus giving us only one token for the entire contents of the stream.

Example 5: Java convert FileInputStream to String

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 inputstream into string.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

17 thoughts on “Java InputStream to String”

  1. Hi I have the data in the notepad like below:
    [VERSION_NUMBER]
    version_number = 1.0.0
    [MULTIBACK]
    BACK= 44C0E0B36BD26.JPG
    BACK2= 0E0B36BD2C.JPG
    [VIOLATOR_HEADER_1]
    num = 0
    Total = 1
    Possible = 0

    So i have get all the data and store in the string but I need to select any one field and edit that field how can do that please let me know

    Reply
  2. Hey , I am trying to read the data from InputStream and want to make it as a string so how can i do that.
    I have read somewhere we can use JsonReader but in tomcat server i can’t able to process Json Request because its showing me Caused by: java.lang.ClassNotFoundException: org.glassfish.json.JsonProviderImpl

    Reply
  3. There is a bug in your implementation of 1). You need to insert a new-line character for each line read, otherwise the resulting string will be incorrect. HTH

    Reply
  4. Sir i have a string
    String s= “B55627&827,1101111”;
    I need to read this string as follows :-
    int a = Integer.parseInt(s.substring(0,4));
    int b = Integer.parseInt(s.substring(4,8));
    int c = Integer.parseInt(s.substring(8,11));
    int d = Integer.parseInt(s.substring(11, 13))
    int e = Integer.parseInt(s.substring(13, 15));
    int f = Integer.parseInt(s.substring(15, 17));
    But i am only reading the first line not able to read the next lines at all.
    What should I do sir

    Reply
  5. I have main and class code but I am getting confused where to put the code for reading a stream of data. In class I have the code that has data separately. I need to put all those data in a stream and read that as a string. I have created in public class type. can you guide me as how should I proceed further.

    Reply
      • I have received TCP packet through codewarrior software in C language. I need to capture that packet and segregate into certain bytes as header is of 4 bytes and data is of 3 bytes each and unpacket it to get the original information / data. Please provide the code to do so

        Reply
  6. 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

    Reply
  7. 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));

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.