获取一个输出流到一个字符串中 [英] Get an OutputStream into a String
问题描述
将 java.io.OutputStream 的输出通过管道传输到 Java 中的字符串的最佳方法是什么?
What's the best way to pipe the output from an java.io.OutputStream to a String in Java?
说我有方法:
writeToStream(Object o, OutputStream out)
将对象中的某些数据写入给定的流.但是,我想尽可能轻松地将此输出转换为字符串.
Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.
我正在考虑编写一个这样的类(未经测试):
I'm considering writing a class like this (untested):
class StringOutputStream extends OutputStream {
StringBuilder mBuf;
public void write(int byte) throws IOException {
mBuf.append((char) byte);
}
public String getString() {
return mBuf.toString();
}
}
但是有更好的方法吗?我只想做个测试!
But is there a better way? I only want to run a test!
推荐答案
我会使用 ByteArrayOutputStream
.完成后您可以调用:
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
或更好:
baos.toString( codepage );
对于 String
构造函数,codepage
可以是 String
或 java.nio.charset.Charset.一个可能的值是 java.nio.charset.StandardCharsets.UTF_8.
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
方法 toString()
只接受一个 String
作为 codepage
参数(支持 Java 8).
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
这篇关于获取一个输出流到一个字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!