The InputStreamReader
class provides a read()
method to read data from an InputStream into a character array. We can convert the char array to a string. Create a new Java source file InputStreamToString.java
in the ~/project
directory with the following content:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class InputStreamToString {
public static String inputStreamToString(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
char[] charArray = new char[256];
reader.read(charArray);
return new String(charArray);
}
public static void main(String[] args) {
try {
InputStream input = new ByteArrayInputStream("hello world".getBytes());
String strFromInputStream = inputStreamToString(input);
System.out.print("String from the Input Stream is: " + strFromInputStream);
} catch(Exception e) {
System.out.print(e);
}
}
}
To run the code, open the terminal, then compile and run the code with the following command:
javac InputStreamToString.java && java InputStreamToString