1、使用String构造函数转换
byte[] bytes = new byte[0];
bytes = new byte[inputStream.available()];
inputStream.read(bytes);
String str = new String(bytes);
2、使用BufferedReader、collect和Collectors转换
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining(System.lineSeparator()));
3、使用BufferedReader转换
InputStream inputStream = resource.getInputStream();
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
String str = sb.toString();
System.out.println("输出"+str );
4、使用Scanner转换
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String str = s.hasNext() ? s.next() : "";
或者
String resource = new Scanner(inputStream).useDelimiter("\\Z").next();
return resource;
5、使用BufferedInputStream和ByteArrayOutputStream转换
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
String str = buf.toString();
return str;
6、使用Apache Common中IOUtils.toString()转换
String str = IOUtils.toString(inputStream, "utf-8");
或者
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8.name());
String str = writer.toString();
7、使用Google Guava中CharStreams.toString()转换
String str = CharStreams.toString(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
相关文档:
Java 使用Stream I/O(InputStream/OutputStream)读写文件的方法及示例代码