In this post under Apache Commons IO, I will show with example how to convert a String to InputStream.
“IOUtils” class in Apache Commons IO framework provides a method named “toInputStream” which converts a String to InputStream.
This method takes two arguments
1) instance of String class
2) Charset type
Below is the main class showing how to use this method.
Main class
package ioutils;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Example5 {
public static void main(String[] args) throws IOException {
String input = """
No man is a true believer unless he desires for his brother that which he desires for himself. -Prophet
Limits are what separates us from animals. -Satyameva Jayate
For a new start, it is necessary to end what is going on - Murder
A person gets a reply from the place where he is scared to go - Murder 3
The strong man who has known power all his life, may lose respect for that power, but a weak man knows the value of strength, and knows compassion. - Captain America The first Avenger
A person is a fool if he knows just the truth and not the difference between the truth and the lie - Badla""";
try(InputStream inputStream = IOUtils.toInputStream(input, StandardCharsets.UTF_8);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String data = bufferedReader.readLine();
while(data != null) {
System.out.println(data);
data = bufferedReader.readLine();
}
}
}
}
In the above code, at line 10, I declare and initialize the input string.
At line 18 within try-with-resources block, I call “IOUtils” “toInputStream” method and pass the input string and type of charset as argument.
Then I read the data from input stream and print it out in the console.
In this way we can convert String to InputStream using Apache Commons IO framework.