Convert InputStream to String in Java

A String in Java is a data type that represents a sequence of characters, such as the phrase "Hello World!". It serves as a container for holding textual data. On the other hand, a Stream is an input/output class that facilitates the reading and writing of data in the form of a continuous sequence of bytes.

In certain scenarios, there arises a need to convert streams to strings. This typically occurs when we want to process or manipulate the data within the stream as text. The following two examples demonstrate different approaches for converting an InputStream, which is a type of stream that reads bytes, into 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); } } }

Conclusion

These examples showcase different approaches to convert an InputStream to a String, allowing for further processing, manipulation, or display of the textual data contained within the stream.