In this post, we will learn various ways of converting input stream to String

In this example, we will see that InputStream will be converted to String using java8 streams and String Builder

  • In readFromStreamUsingJava8, we used BufferedReader.lines() and which will take care of converting stream to and below is the source from Java
    • Returns a Stream, the elements of which are lines read from this BufferedReader.
    • Stream lazily populated, i.e., read only occurs during the terminal operation
    • The reader must not be operated on during the execution of the terminal stream operation. Otherwise, the result of the terminal stream operation is undefined.
  • In readFromStream or readUsingInputStream are using readBytes or read metods which are old. Recommended is to use Java8 to read from input stream
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;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
/**
 * 
 * @author Javasavvy: Convert Input Stream to String
 *
 */
public class InputStreamToString {

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

		readUsingInputStream();
		readFromStreamUsingJava8();
		readUsingInputStream();
	}

	public static void readFromStreamUsingJava8() throws FileNotFoundException {
		InputStream inStream = new FileInputStream(new File("E:\\textfile.txt"));
		String result = new BufferedReader(new InputStreamReader(inStream)).lines().collect(Collectors.joining("\n"));
		System.out.println(result);
	}

	public static void readFromStream() throws IOException {
		InputStream inStream = new FileInputStream(new File("E:\\textfile.txt"));
		char[] buffer = new char[1024];
		StringBuilder sb = new StringBuilder();
		Reader in = new InputStreamReader(inStream, StandardCharsets.UTF_8);
		for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0;) {
			sb.append(buffer, 0, numRead);
		}
		System.out.println(sb.toString());
	}
	
	public static void readUsingInputStream() throws IOException {
		InputStream inStream = new FileInputStream(new File("E:\\textfile.txt"));
		StringBuilder sb = new StringBuilder();
		for (int ch; (ch = inStream.read()) != -1; ) {
		    sb.append((char) ch);
		}
		System.out.println(sb.toString());
	}
}

Thanks for reading..