How do I convert a String to an InputStream in Java?

2021-6-3 anglehua

Given a string:

String exampleString = "example";

How do I convert it to an InputStream?


Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".



I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.IOUtils.toInputStream(source, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.



采集自互联网,如有侵权请联系本人

Powered by emlog 京ICP备15036472号-3 sitemap