Java Program to Convert String to InputStream
Last Updated :
12 Jun, 2021
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations.
Illustration:
Input : String : "Geeks for Geeks"
Output : Input Stream : Geeks for Geeks
Input : String : "A computer science portal"
Output : Input stream : A computer science portal
In order to reach the goal, we need to use ByteArrayInputStream. So let us discuss how it’s done?
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
Approach:
- Get the bytes of the String.
- Create a new ByteArrayInputStream using the bytes of the String
- Assign the ByteArrayInputStream object to an InputStream variable.
- Buffer contains bytes that read from the stream.
- Print the InputStream.
Example:
Java
import java.io.*;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class GFG {
public static void main(String[] args) throws IOException {
String string = "Geeks for Geeks" ;
System.out.print( "String : " + string);
InputStream stream = new ByteArrayInputStream(string.getBytes
(Charset.forName( "UTF-8" )));
BufferedReader br = new BufferedReader( new InputStreamReader(stream));
String str = br.readLine();
System.out.print( "\nInput stream : " );
while (str != null ) {
System.out.println(str);
str = br.readLine();
}
}
}
|
Output
String : Geeks for Geeks
Input stream : Geeks for Geeks
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...