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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:04:39  来源:igfitidea点击:

How to convert outputStream to a byte array?

java

提问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

Create a ByteArrayOutputStream.

创建一个ByteArrayOutputStream.

Grab its content by calling toByteArray()

通过调用获取其内容 toByteArray()

Reference

参考

回答by John

You need to do 2 things

你需要做两件事

  • Using ByteArrayOutputStream write to it
  • Using toByteArray(), you will get the contents as byte[]
  • 使用 ByteArrayOutputStream 写入它
  • 使用 toByteArray(),您将获得内容为 byte[]

You could even extend it as mentioned here

你甚至可以像这里提到的那样扩展它

回答by Dillon Ryan Redding

You could simply declare your output stream as a ByteArrayOutputStreamthen use ByteArrayOutputStream#toByteArray().

您可以简单地将输出流声明为ByteArrayOutputStreamthen use ByteArrayOutputStream#toByteArray()

回答by PNS

If the OutputStreamobject supplied is not already a ByteArrayOutputStream, one can wrapit 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 superin 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 问题中找到更详细的讨论。