Java - How to convert InputStream to String

Posted on November 13, 2016


Using java.util.Scanner class we can convert the InputStream to String. The following is an example of converting an InputStream to String.

InputStreamToStringExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;

/**
 * @author imssbora
 */
public class InputStreamToStringExample {
	public static void main(String[] args) {
		File file=new File("file.txt");
		FileInputStream fileInputStream=null;
		try {
			fileInputStream=new FileInputStream(file);
			String text=InputStreamToStringExample.streamToString(fileInputStream);
			System.out.println(text);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static String streamToString(InputStream inputStream){
		@SuppressWarnings("resource")
		Scanner scanner=new Scanner(inputStream).useDelimiter("\\A");
		try {
			return scanner.next();
		} finally {
			scanner.close();
		}
		
	}
}

Output

This is an example of 
converting InputStream to
String.