Signup/Sign In

How to convert inputstream to string in Java

In this post, we are going to read a file using InputStream and then convert it into the string. It is very useful to know the conversion and required for file handling operations.

To convert the InputStream, there are several ways from which two are described below. We used Java Scanner class and Java 8 Stream concept to convert a stream to string.

Here, we have a sample file abc.txt that contains some data and read by the Scanner class.

// abc.txt

Welcome to Studytonight.com
It is technical portal.

Time for an Example:

Let's create an example to get a string from an InputStream. InputStream is an interface in Java that is used to read a file and we used nextLine() method of Scanner class to read the file data and return a string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) throws IOException{  
		File file = new File("abc.txt");
        InputStream is = new FileInputStream(file);
        Scanner s = new Scanner(is);
        String s1 = "";
        while(s.hasNext()) {
        	s1 += s.nextLine()+"\n";
        }
        System.out.println(s1);
        is.close();
	}
}


Welcome to Studytonight.com
It is technical portal.

Time for another Example:

There is another way to get String from InputStream such as using the lines() method that returns a stream of data which further is collected by collect() method and returns as a string. At the end make sure you close the file connection properly.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class Main {
	public static void main(String[] args) throws IOException{  
		File file = new File("abc.txt");
        InputStream is = new FileInputStream(file);
        String result = new BufferedReader(new InputStreamReader(is))
        		  .lines().collect(Collectors.joining("\n"));
        System.out.println(result);
        is.close();
	}
}


Welcome to Studytonight.com
It is technical portal.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.