目录
1、使用com.google.common.io.ByteSource
2、使用com.google.common.io.CharStreams
1、使用org.apache.commons.io.IOUtils.copy()
2、使用org.apache.commons.io.IOUtils.toString()
2、使用java.io.ByteArrayOutputStream
3、使用java.io.InputStream.readAllBytes() (since JDK9)
由于将InputStream转化为String使用很频繁,所以将常用的几种方式列举如下:
一、Google Guava IO
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
1、使用com.google.common.io.ByteSource
// com.google.common.io.ByteSource
public static String toString(InputStream inputStream) throws IOException {
ByteSource byteSource = new ByteSource() {
public InputStream openStream() throws IOException {
return inputStream;
}
};
return byteSource.asCharSource(StandardCharsets.UTF_8).read();
}
2、使用com.google.common.io.CharStreams
// com.google.common.io.CharStreams
public static String toString(InputStream inputStream) throws IOException {
String text = null;
try (final Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
text = CharStreams.toString(reader);
}
return text;
}
二、Apache Commons IO
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
1、使用org.apache.commons.io.IOUtils.copy()
public static String toString(InputStream inputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
return writer.toString();
}
2、使用org.apache.commons.io.IOUtils.toString()
public static String toString(InputStream inputStream) throws IOException {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
三、JDK
1、使用java.util.Scanner
public static String toString(InputStream inputStream) throws IOException {
// \A The beginning of the input
// \Z The end of the input but for the final terminator, if any
// \z The end of the input
try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());) {
scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
}
2、使用java.io.ByteArrayOutputStream
public static String toString(InputStream inputStream) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
bout.write(buf, 0, len);
}
return bout.toString(StandardCharsets.UTF_8.name());
}
3、使用java.io.InputStream.readAllBytes()(since JDK9)
public static String toString(InputStream inputStream) throws IOException {
// since JDK9
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
参考文档