且构网

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

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

更新时间:2023-02-17 09:07:31

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();

or even

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

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