且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 中读取/将 InputStream 转换为字符串?

更新时间:2023-02-17 09:04:05

一个很好的方法是使用 Apache commons IOUtilsInputStream 复制到 StringWriter 中......类似

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

甚至

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

或者,如果您不想混合流和写入器,您可以使用 ByteArrayOutputStream

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers