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:

Spring Security Basic Authentication
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Hướng dẫn Java Design Pattern – Factory Method
Java Program to Find Maximum Element in an Array using Binary Search
Java Program to Implement Aho-Corasick Algorithm for String Matching
Java Program to Solve TSP Using Minimum Spanning Trees
Python Program to Compute all the Permutation of the String
Jackson Annotation Examples
Java Program to Find Transpose of a Graph Matrix
Jackson – JsonMappingException (No serializer found for class)
Guide to the Volatile Keyword in Java
Guide to Java 8’s Collectors
Stack Memory and Heap Space in Java
Java Program to Implement LinkedBlockingQueue API
Java Program to Implement Max-Flow Min-Cut Theorem
Giới thiệu Aspect Oriented Programming (AOP)
Debugging Reactive Streams in Java
Java Program to Implement Levenshtein Distance Computing Algorithm
New in Spring Security OAuth2 – Verify Claims
Java Program to Compute DFT Coefficients Directly
Java Program to Compute Determinant of a Matrix
Apache Commons Collections SetUtils
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Overflow and Underflow in Java
Giới thiệu Swagger – Công cụ document cho RESTfull APIs
File Upload with Spring MVC
Spring Boot - Cloud Configuration Server
Easy Ways to Write a Java InputStream to an OutputStream
Python String islower()
Java Program to Implement Suffix Array
Java Program to Perform Matrix Multiplication