Java 如何将 outputStream 转换为字节数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23154009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert outputStream to a byte array?
提问by hellzone
How can I convert an OutputStream to a byte array? I have found that first I need to convert this OutputStream to a ByteArrayOutputStream. There is only write() method in this OutputStream class and I don't know what to do. Is there any idea?
如何将 OutputStream 转换为字节数组?我发现首先我需要将此 OutputStream 转换为 ByteArrayOutputStream。这个 OutputStream 类中只有 write() 方法,我不知道该怎么做。有什么想法吗?
采纳答案by Washcloth
回答by John
回答by Dillon Ryan Redding
You could simply declare your output stream as a ByteArrayOutputStream
then use ByteArrayOutputStream#toByteArray()
.
您可以简单地将输出流声明为ByteArrayOutputStream
then use ByteArrayOutputStream#toByteArray()
。
回答by PNS
If the OutputStream
object supplied is not already a ByteArrayOutputStream
, one can wrap
it inside a delegate class that will "grab" the bytes supplied to the write()
methods, e.g.
如果OutputStream
提供的对象还不是 a ByteArrayOutputStream
,则可以将wrap
它放在一个委托类中,该类将“抓取”提供给write()
方法的字节,例如
public class DrainableOutputStream extends FilterOutputStream {
private final ByteArrayOutputStream buffer;
public DrainableOutputStream(OutputStream out) {
super(out);
this.buffer = new ByteArrayOutputStream();
}
@Override
public void write(byte b[]) throws IOException {
this.buffer.write(b);
super.write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
this.buffer.write(b, off, len);
super.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
this.buffer.write(b);
super.write(b);
}
public byte[] toByteArray() {
return this.buffer.toByteArray();
}
}
To reduce the overhead, the calls to super
in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired.
为了减少开销,super
可以省略上述类中的调用- 例如,如果只需要“转换”到字节数组。
A more detailed discussion can be found in another StackOverflow question.
可以在另一个 StackOverflow 问题中找到更详细的讨论。