This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

How to convert a string to an InputStream in Java?

Given a string:

String exampleString = “example”;

How do I convert it to an InputStream?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Like this:

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

Note that this assumes you need an InputStream, which is a byte stream that represents the raw string encoded as UTF-8.

For Java versions less than 7, replace StandardCharsets.UTF_8 with “UTF-8”.

Answer:

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");
Copy the code

You may find that the library also provides many other shortcuts for common tasks that you can use in your projects.

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 7…

Authors suggest: There is also a previous article:How do I read/convert an input stream to a string in Java?

There are professional Benchmark tests in this article, and I’ll take a screenshot here

Using ByteArrayOutputStream performance is great!


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️