Exercise:
Write a Java Program to convert InputStream to string.
Click Here to View the Solution!
import java.io.*;
public class InputStreamString {
public static void main(String[] args) throws IOException {
InputStream stream = new ByteArrayInputStream("Hello World!".getBytes());
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
System.out.println(sb);
}
}
Click Here to View the Output!
Hello World!
Click Here to View the Explanation!
- This program deals with the transformation of a text stream of characters into a string by employing
InputStreamReader
. - In the first statement of main function, byte sequence/ stream of string “Hello World!” is obtained via
ByteArrayInputStream()
function and is contained in ‘stream’ variable. - The next step is to employ
StringBuilder()
function to convert the contents of ‘stream’ into a modifiable array of characters. - The very next step involves reading those contents stored in
stream
, for that purpose firstInputStreamReader()
converts byte sequence of ‘stream’ into characters; then ‘stream’ is read usingBufferedReader()
. InputStream
is read line by line throughwhile loop
; also during each iteration those lines are appended to string builder objectsb
.- After that buffer is closed and result is displayed on the console.
- In order to avoid any invalid input,
IOException
has been employed.