Today we will look into how to convert String to InputStream in java. Recently I wrote a post to convert InputStream to String.

Java String to InputStream

Java-String-to-InputStream
There are two ways that I have used to convert String to InputStream.

  1. Java IO ByteArrayInputStream class
  2. Apache Commons IO IOUtils class

Let’s have a look at example program to use these classes.

Java String to InputStream using ByteArrayInputStream


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class StringToInputStreamUsingByteArrayInputStream {
	public static void main(String[] args) throws IOException {
		String str = "convert String to Input Stream Example using ByteArrayInputStream";
		// convert using ByteArrayInputStream
		InputStream is = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8")));
		// print it to console
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = br.readLine();
		while (line != null) {
			System.out.println(line);
			line = br.readLine();
		}
	}
}

String to InputStream using Apache Commons IOUtils


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
public class StringToInputStreamUsingIOUtils {
	public static void main(String[] args) throws IOException {
		String str = "Example using Apache Commons IO class IOUtils";
		InputStream stream = IOUtils.toInputStream(str, Charset.forName("UTF-8"));
		stream.close();
	}
}

You can use IOUtils if you are already using Apache Commons IO jars, otherwise there is no benefit since internally it’s using ByteArrayInputStream class. Below is the toInputStream method implementation from IOUtils class source code.


public static InputStream toInputStream(final String input, final Charset encoding) {
        return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding)));
    }

That’s all about converting String to Input Stream in java.

By admin

Leave a Reply

%d bloggers like this: