Convert String InputStream Java
In below sample java program we will convert String to InputStream. I will show you two way to convert. In first example we will use ByteArrayInputStream and second example will use Apache commons (Preferred approach):
Sample java program:
package com.javahonk; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; public class ConvertStringInputStream { public static void main(String[] args) { try { String sampleString = "Convert String to InputStream Java"; //Example 1: Using ByteArrayInputStream InputStream stream = new ByteArrayInputStream(sampleString.getBytes(StandardCharsets.UTF_8)); String convertedString = IOUtils.toString(stream, "UTF-8"); System.out.println("Example 1: "+convertedString); // Example 2: Using Apache Commons InputStream inputStream = IOUtils.toInputStream(sampleString, "UTF-8"); convertedString = IOUtils.toString(inputStream, "UTF-8"); System.out.println("Example 2: "+convertedString); } catch (IOException e) { e.printStackTrace(); } } }
- Output:
For more information about convert string read oracle documentation here