在Java中,有几种方法可以将InputStream
转换为String
:
1.纯Java – ByteArrayOutputStream
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name());
}
2.如果是Java 9,请尝试以下inputStream.readAllBytes
:
private static String convertInputStreamToStringJDK9(InputStream inputStream)
throws IOException {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
3. Apache Commons IO – IOUtils.copy
pom.xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
private static String convertInputStreamToStringCommonIO(InputStream inputStream)
throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
return writer.toString();
}
1.将InputStream转换为String
InputStreamToString.java
package com.mkyong;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;
public class InputStreamToString {
public static void main(String[] args) throws IOException {
URI u = URI.create("https://www.google.com/");
try (InputStream inputStream = u.toURL().openStream()) {
// InputStream -> String
String result = convertInputStreamToString(inputStream);
System.out.println(result);
}
}
// Pure Java
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name());
}
// Since Java 9
private static String convertInputStreamToStringJDK9(InputStream inputStream) throws IOException {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
// commons-io
private static String convertInputStreamToStringCommonIO(InputStream inputStream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);
return writer.toString();
}
}
参考文献
- InputStream.readAllBytes JavaDocs
- ByteArrayOutputStream JavaDocs
- Apache Commons IO
- 如何在Java中将String转换为InputStream
翻译自: https://mkyong.com/java/how-to-convert-inputstream-to-string-in-java/