Convert InputStream to String in Java
Description
The following code shows how to convert InputStream to String.
Example
//ww w.j av a 2s . c o m
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
InputStream is = Main.class.getResourceAsStream("/data.txt");
System.out.println(convertStreamToString(is));
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
}
The code above generates the following result.