
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: January 5, 2024
In this quick tutorial, we’re going to look at how to convert a standard String to an InputStream using plain Java, Guava and the Apache Commons IO library.
This tutorial is part of the Java – Back to Basics series here on Baeldung.
Let’s start with a simple example using Java to do the conversion — using an intermediary byte array:
@Test
public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect()
throws IOException {
String initialString = "text";
InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
}
The getBytes() method encodes this String using the platform’s default charset, so to avoid undesirable behavior, we can use getBytes(Charset charset) and control the encoding process.
Guava doesn’t provide a direct conversion method but does allow us to get a CharSource out of the String and easily convert it to a ByteSource.
Then it’s easy to obtain the InputStream:
@Test
public void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect()
throws IOException {
String initialString = "text";
InputStream targetStream =
CharSource.wrap(initialString).asByteSource(StandardCharsets.UTF_8).openStream();
}
The asByteSource method is in fact marked as @Beta. This means it can be removed in the future Guava release. We need to keep this in mind.
Finally, the Apache Commons IO library provides an excellent direct solution:
@Test
public void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect()
throws IOException {
String initialString = "text";
InputStream targetStream = IOUtils.toInputStream(initialString);
}
Note that we’re leaving the input stream open in these examples, so don’t forget to close it.
In this article, we presented three simple and concise ways to get an InputStream out of a simple String.