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 Implement Min Hash
Java Program to implement Array Deque
Java Program to Implement Rope
Python String replace()
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
A Guide to Spring Cloud Netflix – Hystrix
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
Java Program to Find Transitive Closure of a Graph
Wrapper Classes in Java
Spring Boot - Zuul Proxy Server and Routing
Python Program to Parse a String to a Float or Int
Python String endswith()
Kết hợp Java Reflection và Java Annotations
Logout in an OAuth Secured Application
Guide to the Java Clock Class
Encode/Decode to/from Base64
Java Program to Check whether Undirected Graph is Connected using BFS
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
The Spring @Controller and @RestController Annotations
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Phân biệt JVM, JRE, JDK
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
Spring Security – security none, filters none, access permitAll
Handling URL Encoded Form Data in Spring REST
Setting a Request Timeout for a Spring REST API
Getting the Size of an Iterable in Java
Java Program to Implement Self Balancing Binary Search Tree
Transaction Propagation and Isolation in Spring @Transactional
Extra Login Fields with Spring Security
Registration – Activate a New Account by Email
Period and Duration in Java
So sánh Array và ArrayList trong Java