Learn to convert Java String to InputStream using ByteArrayInputStream
and IOUtils
classes. Writing String to Steam is a frequent job in Java and having a couple of good shortcuts will prove useful.
Read More: Converting InputStream to String
1. ByteArrayInputStream
Using ByteArrayInputStream is simplest way to create InputStream from string. using this approach, we do not need any external dependency.
Example 1: Creating an InputStream from a String
The getBytes()
method encodes the String into a sequence of bytes using the platform’s default charset. To use a different charset, use the method getBytes(Charset charset)
.
The StandardCharsets
class provides the constant definitions for the standard charsets. For example, StandardCharsets.UTF_8
.
import java.io.ByteArrayInputStream; import java.io.InputStream; public class ConvertStringToInputStreamExample { public static void main(String[] args) { String sampleString = "howtodoinjava.com"; //Here converting string to inputstream InputStream stream = new ByteArrayInputStream(sampleString.getBytes()); } }
2. IOUtils – Apache Commons IO
IOUtils is very useful class for IO operations in Java. This solution is also pretty good because apache commons is very much a mostly included jar in most applications.
IOUtils.toInputStream()
makes code very much readable. It is an overloaded method so use the desired encoding while invoking this method.
static InputStream toInputStream(String input) //Deprecated static InputStream toInputStream(String input, Charset encoding) static InputStream toInputStream(String input, String encoding)
Example 2: How to create InputStream from a String in Java
import java.io.InputStream; import org.apache.commons.io.IOUtils; public class ConvertStringToInputStreamExample { public static void main(String[] args) { String sampleString = "howtodoinjava.com"; //Here converting the string to the inputstream InputStream stream = IOUtils.toInputStream(sampleString, StandardCharsets.UTF_8); } }
Happy Learning !!
WolframG
I hoped that solution #2 would be a bit more memory efficient than to duplicate the entire string as byte array. But when looking at the sources it turns out that #1 is exactly what is used inside #2.
Lokesh Gupta
🙂 So it turned out to be only little more readable code.