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:

Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Jackson – Change Name of Field
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Perform Cryptography Using Transposition Technique
New Features in Java 9
A Guide to JUnit 5
Introduction to Project Reactor Bus
Send an email using the SMTP protocol
Assertions in JUnit 4 and JUnit 5
An Intro to Spring Cloud Security
Python Program to Get a Substring of a String
Java Program to Implement Find all Forward Edges in a Graph
Lập trình đa luồng với CompletableFuture trong Java 8
How to Get All Dates Between Two Dates?
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Create a Custom Auto-Configuration with Spring Boot
Remove the First Element from a List
Java Program to Implement Binary Heap
Hướng dẫn Java Design Pattern – Null Object
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Implement Hash Tree
Java Program to Implement Weight Balanced Tree
An Introduction to ThreadLocal in Java
Spring Boot - Actuator
Java Program to Evaluate an Expression using Stacks
OAuth 2.0 Resource Server With Spring Security 5
Java – Random Long, Float, Integer and Double
Java Program to Find the Longest Path in a DAG
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Java 8 StringJoiner
Java Program to Perform integer Partition for a Specific Case