Java Convert String to InputStream

Tags: InputStream String

In this Java tutorial we learn how to use Java core API to convert a String value into an InputStream object in Java programming language.

How to convert String to InputStream in Java

In Java we can convert a String to byte[] array and then convert it to ByteArrayInputStream object as below.

String data = "Simple Solution";
byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(byteData);

In the following Java example program, we use the above solution to convert a String intoto ByteArrayInputStream object and then write it to a file.

StringToInputStreamExample1.java

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class StringToInputStreamExample1 {
    public static void main(String... args) throws IOException {
        String data = "Simple Solution";

        // Convert String to byte array
        byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
        // convert byte array to InputStream
        InputStream inputStream = new ByteArrayInputStream(byteData);

        long numberOfBytes = Files.copy(inputStream, Paths.get("D:\\SimpleSolution\\data.txt"));
        System.out.println("Successful write " + numberOfBytes + " bytes to file");
    }
}
The output as below.
Successful write 15 bytes to file

Happy Coding 😊

Java Encode String to Base64 String

Java Convert String to Byte Array