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:
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!
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! ❤ ️ ❤ ️ ❤ ️ ❤ ️