Convert InputStream to String in Java

String is a sequence of characters used to hold data like "Halo World!". A Stream is an i/o class that is used to read and write bytes of data as a continuous sequence of bytes. In some situations we need to convert streams to string . The following 2 examples show how to convert an InputStream to a String.

Using Scanner Class:

import java.io.*; import java.util.*; public class TestClass{ public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("in.txt"); String str = new Scanner(fis,"UTF-8").useDelimiter("\\A").next(); System.out.println(str); } catch (Exception e) { System.err.println(e); } } }

Using BufferedInputStream and ByteArrayOutputStream

import java.io.*; import java.util.*; public class TestClass{ public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("in.txt"); BufferedInputStream bStream = new BufferedInputStream(fis); ByteArrayOutputStream baous = new ByteArrayOutputStream(); int temp = bStream.read(); while(temp != -1) { baous.write((byte) temp); temp = bStream.read(); } String str = baous.toString("UTF-8"); System.out.println(str); }catch (IOException e) { System.err.println(e); } } }