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 Generate All Possible Subsets with Exactly k Elements in Each Subset
Java program to Implement Tree Set
Inject Parameters into JUnit Jupiter Unit Tests
Mảng (Array) trong Java
Java Program to Implement Sieve Of Atkin
Python String lower()
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Autoboxing và Unboxing trong Java
Kết hợp Java Reflection và Java Annotations
How to Kill a Java Thread
Notify User of Login From New Device or Location
Hướng dẫn Java Design Pattern – Decorator
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement Bresenham Line Algorithm
Java Program to Implement Dijkstra’s Algorithm using Queue
Instance Profile Credentials using Spring Cloud
Recommended Package Structure of a Spring Boot Project
Guide to UUID in Java
Stack Memory and Heap Space in Java
Overview of Spring Boot Dev Tools
Java Program to Implement Shoelace Algorithm
Java Program to Implement Meldable Heap
Serialize Only Fields that meet a Custom Criteria with Jackson
Java Program to Check whether Directed Graph is Connected using DFS
Java Program to Implement Interpolation Search Algorithm
Testing in Spring Boot
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Changing Annotation Parameters At Runtime
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Simple Single Sign-On with Spring Security OAuth2
Request a Delivery / Read Receipt in Javamail
Java Program to implement Associate Array