Java Program to Convert String to InputStream
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations.
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.
- 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.
String : Geeks for Geeks Input stream : Geeks for Geeks
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.