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 – Write an InputStream to a File
Java Program to Perform the Sorting Using Counting Sort
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement Triply Linked List
Comparing Two HashMaps in Java
Java Program to Encode a Message Using Playfair Cipher
Tiêu chuẩn coding trong Java (Coding Standards)
Sending Emails with Java
Java Program to Implement Repeated Squaring Algorithm
Multi Dimensional ArrayList in Java
Guide to the ConcurrentSkipListMap
Java Program to Implement Sorted Array
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
Java Program to Implement Uniform-Cost Search
Java Program to Generate Random Numbers Using Probability Distribution Function
Java Program to Implement Suffix Tree
Java – InputStream to Reader
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Easy Ways to Write a Java InputStream to an OutputStream
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
The Registration API becomes RESTful
Sort a HashMap in Java
Java Program to Describe the Representation of Graph using Adjacency List
Java Program to Solve any Linear Equation in One Variable
Hướng dẫn sử dụng Printing Service trong Java
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Hướng dẫn Java Design Pattern – Singleton
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Guide to Guava Table
A Guide to Queries in Spring Data MongoDB
Supplier trong Java 8
Spring Boot Change Context Path