public String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the BufferedReader
* return null which means there's no more data to read. Each line will
* appended to a StringBuilder and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line); // + "/n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
本文介绍了一种将Java中的InputStream转换为String的有效方法。通过使用BufferedReader读取输入流,并逐行构建StringBuilder,最终将其转换为字符串。文章还展示了如何处理可能发生的IOException异常,并确保输入流在完成后被正确关闭。
7004

被折叠的 条评论
为什么被折叠?



