java将InputStream转为String
public static String inputStream2String(InputStream is, String charset) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString(charset);
} catch (IOException e) {
e.printStackTrace();
logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"
+ e.getMessage());
} finally {
if (null != baos) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("FileWRUtil.inputStream2String(InputStream is, String charset) occur error:"
+ e.getMessage());
}
baos = null;
}
}
return null;
}
其中
return baos.toString(charset);
这行很重要,如果不填写放回的字符编码,对中午来说就容易出现乱码,可以是GBK 、UTF-8等,看项目实际编码即可;