In Java, both HashMap and Hashtable are used to store key-value pairs, but there are…
How do I read / convert an InputStream into a String in Java?
To convert an InputStream
into a String
in Java, you can use the following steps:
- Create a
StringBuilder
object to efficiently build the string. - Create a
BufferedReader
object, passing theInputStream
wrapped in anInputStreamReader
. This allows you to read the input stream line by line. - Use a loop to read each line from the
BufferedReader
and append it to theStringBuilder
object. - Finally, convert the
StringBuilder
object to aString
.
Here’s an example code snippet that demonstrates the process:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class InputStreamToStringExample {
public static String convertInputStreamToString(InputStream inputStream) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
}
return stringBuilder.toString();
}
public static void main(String[] args) {
InputStream inputStream = ...; // Your InputStream instance
try {
String result = convertInputStreamToString(inputStream);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the code above, convertInputStreamToString()
is a utility method that takes an InputStream
as an argument and returns the converted String
. The try-with-resources
statement is used to ensure proper closing of the BufferedReader
after use.
Note: In this example, the InputStream
is assumed to be encoded in UTF-8. If your input stream is encoded differently, you can specify the appropriate character encoding by modifying the InputStreamReader
constructor parameter.
This Post Has 0 Comments