Java: Convert String to InputStream


You can convert a Java String to InputStream using the ByteArrayInputStream class from the java.io package.


Example:
package org.code2care.java.examples;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class JavaStringToInputStreamExample {
    
    public static void main(String[] args) throws IOException {

        String inputString = "This is a input string!";
        byte[] byteArr = inputString.getBytes();
        InputStream inputStream = new ByteArrayInputStream(byteArr);

        int nextByteData;
        while ((nextByteData = inputStream.read()) != -1) {
            System.out.print((char) nextByteData);
        }

    }
}

Note that you can also use StringBufferInputStream to achieve the same, but it has been deprecated since Java 1.1 and should be avoided.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap