Home > Java > javaTutorial > body text

How to Convert a String to an InputStream in Java?

Mary-Kate Olsen
Release: 2024-10-27 00:20:03
Original
544 people have browsed it

How to Convert a String to an InputStream in Java?

Converting a String to an InputStream in Java

When working with text data, it can be essential to convert strings into input streams for further processing. In Java, this conversion is straightforward and involves using the ByteArrayInputStream class.

Let's say we have a string stored in a variable named exampleString:

<code class="java">String exampleString = "example";</code>
Copy after login

To convert it to an input stream, you can use the following code:

<code class="java">InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));</code>
Copy after login

The getBytes() method converts the string into an array of bytes using the UTF-8 encoding, which is the default in Java. The resulting byte array is then used to create an input stream that can be used for reading the data as bytes.

This approach assumes that you want the input stream to contain a sequence of bytes representing the original string encoded as UTF-8.

Note for Java Versions Less Than 7

For versions of Java prior to 7, where the StandardCharsets class is not available, you can use the following code instead:

<code class="java">InputStream stream = new ByteArrayInputStream(exampleString.getBytes("UTF-8"));</code>
Copy after login

The above is the detailed content of How to Convert a String to an InputStream in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!