Java String to InputStream

1. Overview

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 article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

2. Convert With Plain Java

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());
}

Note that the getBytes() method encodes this String using the platform’s default charset so to avoid undesirable behavior you can use getBytes(Charset charset) and control the encoding process.

3. Convert With Guava

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, obtaining the InputStream is easy:

@Test
public void givenUsingGuava_whenConvertingStringToInputStream_thenCorrect() 
  throws IOException {
    String initialString = "text";
    InputStream targetStream = 
      CharSource.wrap(initialString).asByteSource(StandardCharsets.UTF_8).openStream();
}

Note, however, that the asByteSource method is marked as @Beta. This means it can be removed in the future Guava release. We need to keep this in mind.

4. Convert With Commons IO

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);
}

Finally – do note that we’re leaving the input stream open in these examples – don’t forget to close it when you’re done.

5. Conclusion

In this article, we presented three simple and concise ways to get an InputStream out of a simple String.

As always, the full source code is available over on GitHub.

Related posts:

Hamcrest Collections Cookbook
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Java Program to Implement PrinterStateReasons API
Finding the Differences Between Two Lists in Java
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Spring Boot - Servlet Filter
Chuyển đổi từ HashMap sang ArrayList
Python String upper()
Introduction to the Java NIO2 File API
Java Program to Implement Control Table
Java Program to Generate Random Numbers Using Middle Square Method
Java Program to Implement Cubic convergence 1/pi Algorithm
Java – Random Long, Float, Integer and Double
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Implement Iterative Deepening
Java Program to Use rand and srand Functions
Java Program to Implement Pollard Rho Algorithm
Spring Boot Configuration with Jasypt
Java Program to Delete a Particular Node in a Tree Without Using Recursion
Constructor Dependency Injection in Spring
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Java Program to Implement PriorityBlockingQueue API
Spring Security Form Login
Java Program to Find the Vertex Connectivity of a Graph
Java Program to Create a Balanced Binary Tree of the Incoming Data
Quick Guide on Loading Initial Data with Spring Boot
Difference Between Wait and Sleep in Java
Python String isupper()
Java – File to Reader
A Quick Guide to Using Keycloak with Spring Boot
Spring Security 5 – OAuth2 Login
Consuming RESTful Web Services