Java program to convert inputstream to string
Here is a Java program to convert an InputStream to a String:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ConvertInputStreamToString {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
String inputString = convertInputStreamToString(inputStream);
System.out.println("Input as string: " + inputString);
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
}
This program first creates an InputStream object, inputStream, using the System.in input stream. It then calls the convertInputStreamToString() method to convert the input stream to a string. The convertInputStreamToString() method uses a BufferedReader to read the input stream line by line, and a StringBuilder to append each line to a string. Finally, it returns the completed string.
When you run this program, it will read input from the console until you press "Enter". It will then output the input as a string. Note that this program assumes that the input is text data. If the input is binary data, you will need to use a different method to convert the input stream to a more appropriate format, such as Base64 encoding.
