基本类介绍
InputStream:存储字节流
BufferedReader:存储字符流,并封装了读取字符流方法
InputStreamReader:将字节流转换成字符流
总结:InputStream和BufferedReader是存储载体, InputStreamReader是转换工具
代码
private static String encodeInputStream2String(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
//字节流转换成字符流, 并存储在BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
//读取字符流
while ((line = reader.readLine()) != null) {
sb.append(line);
}
//一定要关闭资源,非常重要
is.close();
reader.close();
return sb.toString();
}