Convert a String to an Input Stream in Java
This post will discuss how to convert the specified string to an input stream in Java, encoded as bytes using the specified character encoding.
1. Using ByteArrayInputStream
The idea is to get a sequence of bytes from the given specified and create a ByteArrayInputStream
from it, as shown below. This works as ByteArrayInputStream
class extends the InputStream
class. We have used StandardCharsets.UTF_8
to specify the charset. Before Java 7, we can use the Charset.forName("UTF-8")
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; // Program to convert a string to `InputStream` in Java class Main { public static void main(String[] args) { String input = "Techie Delight"; try { // get a sequence of bytes from the given string byte[] bytes = input.getBytes(StandardCharsets.UTF_8); // Creates a `ByteArrayInputStream` from the input buffer InputStream in = new ByteArrayInputStream(bytes); // do something // close the input stream in.close(); } catch (IOException e) { e.printStackTrace(); } } } |
2. Using Apache Commons IO
Apache Commons IO IOUtils
class provides several IO stream manipulation utility static methods. One such method is toInputStream()
, which converts the specified string to an input stream using the specified character encoding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; // Program to convert a string to `InputStream` in Java class Main { public static void main(String[] args) { String input = "Techie Delight"; try { InputStream in = IOUtils.toInputStream(input, StandardCharsets.UTF_8); // do something in.close(); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about converting a String to an Input Stream in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)