How to convert String to InputStream in Java

In this post, we will go through different options at how to convert String to InputStream in Java using JDK and Other utility classes.

 

1. Convert String to InputStream in Java

Let’s take a look at the converting String to InputStream using pure Java. We will be using the ByteArrayInputStream to convert String to InputStream.

public class StringToIOJava {

    public static void main(String[] args) throws IOException {
        String inputString = "This is a String to demo as how to convert it to input stream using Core Java API";

        //String to input stream
        try (InputStream inputStream = new ByteArrayInputStream(inputString.getBytes(StandardCharsets.UTF_8));
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            String content;
            while ((content = bufferedReader.readLine()) != null) {
                //work with file
            }
        }
    }
}

It’s always recommended to pass explicit Charset to the method getBytes() to avoid any unwanted behavior.Java will pick platform’s default char-set if not passed to the method.If you are on older version of JDK (Less than 7), make sure to replace StandardCharsets.UTF_8 with "UTF-8".

If you like you can also work on a more simpler version if you want to use the stream for something else.

import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class ConvertStringToInputStream {
    public static void main(String[] args) {

        String inputString = "This is a String to demo as how to convert it to input stream using Core Java API";
        InputStream stream = new ByteArrayInputStream(inputString.getBytes());
        //work with your input stream
    }
}

Let’s understand few basic while converting the String to InputStream in Java:

  1. We are passing the byte array to the ByteArrayInputStream.
  2. The getByte() method encode the String using platform default charset (if no explicit charset is passed).
  3. The getByte() method also provide option to pass the charset using getByte(Charset charset). This is useful when we know the charset of the String and want to control the encoding process.

 

2. Convert String to InputStream Using Apache IOUtils

Apache Commons IO provides provide a lot of convenient method while working on I/O operations in Java.If you are working on a larger application, there are high level of chances that it’s already part of the required dependencies. Also the IOUtils.toInputStream is more readable. Here are the list of overloaded method available in the API.

  1. IOUtils.toInputStream(CharSequence input, Charset encoding)
  2. IOUtils.toInputStream(CharSequence input, String encoding)
  3. IOUtils.toInputStream(String input, Charset encoding)
  4. IOUtils.toInputStream(String input, String encoding)

I am not including the deprecated methods.Let’s see how to use the IOUtils to perform these operations.

public class StringToIOApache {

    public static void main(String[] args) throws IOException {
        String inputString = "This is a String to demo as how to convert it to input stream using Apache Commons IO";
        InputStream inputStream = IOUtils.toInputStream(inputString, StandardCharsets.UTF_8);
    }
}

Make sure you include the jar as dependency.If you are using the Maven/Gradle, add the dependency in the pom.xml or Gradle configuration file.

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>add latest version</version>
</dependency>

 

3. Convert String to InputStream Guava.

If your project using the Google Guava library, it also provides an option to convert String to InputStream in Java.Let’s see how to do this with Guava. If your project is not using it and you like to try , make sure you add the required dependencies either directly or using the Maven or Gradle as your build platform.

import java.io.IOException;
import java.io.InputStream;

import com.google.common.base.Charsets;
import com.google.common.io.CharSource;

public class ConvertStringToInputStream {
    public static void main(String[] args) {

        String inputString = "This is a String to demo as how to convert it to input stream using Core Java API";

        /**
         Convert using Google Guava
         */
        InputStream stream = new ReaderInputStream(CharSource
            .wrap(str)
            .openStream(), Charsets.UTF_8);
    }
}

The pom.xml entry

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>latest version</version>
</dependency>

 

Summary

In this post, we saw how to convert String to InputStream in Java. We can use the JDK method to convert String to InputStream, Apache IOUtils or the Google Guava API to perform the conversion.If you want to convert InputStream to String in Java, please read out article on Convert InputStream to String in Java.