如何在Java中将InputStream读取/转换为String? [英] How do I read / convert an InputStream into a String in Java?
问题描述
如果有一个java.io.InputStream
对象,应该如何处理该对象并产生一个String
?
If you have a java.io.InputStream
object, how should you process that object and produce a String
?
假设我有一个包含文本数据的InputStream
,并且我想将其转换为String
,例如,我可以将其写入日志文件.
Suppose I have an InputStream
that contains text data, and I want to convert it to a String
, so for example I can write that to a log file.
获取InputStream
并将其转换为String
的最简单方法是什么?
What is the easiest way to take the InputStream
and convert it to a String
?
public String convertStreamToString(InputStream is) {
// ???
}
推荐答案
一个很好的方法是使用 Apache commons IOUtils
将InputStream
复制到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);
或者,如果您不想混合使用Streams和Writers,则可以使用ByteArrayOutputStream
Alternatively, you could use ByteArrayOutputStream
if you don't want to mix your Streams and Writers
这篇关于如何在Java中将InputStream读取/转换为String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!