Java convert String to InputStream

Standard Java convert String to InputStream

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

String str = "this is a test string";

try {
InputStream is = new ByteArrayInputStream(str.getBytes("UTF8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

Commons IO convert String to InputStream

You need dependancy in your pom.xml file (or check below for gradle):

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

then simply for newer version( encoding parameter is included):

import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;

try {
    InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(str, "UTF8"));
} catch (IOException e) {
    e.printStackTrace();
}

or for the older versions the encoding parameter is not included:

import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;

String str = "this is a test string";

try {
    InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(str));
} catch (IOException e) {
    e.printStackTrace();
}

Or add

compile 'org.apache.directory.studio:org.apache.commons.io:2.4' 

to the build.gradle

or:

  • File
  • Project Structure...
  • Dependencies
  • Click '+' in the upper right corner
  • select "Library dependency"
  • In the search field type: "org.apache.commons.io"
  • click Search
  • Select "org.apache.directory.studio:org.apache.commons.io: