Java 如何将字节数组转换为 ByteArrayOutputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18575480/
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-12 09:09:11  来源:igfitidea点击:

How to convert Byte array to ByteArrayOutputStream

javabytebytearrayoutputstream

提问by Arun

I need to convert a byte array to ByteArrayOutputStream so that I can display it on screen.

我需要将字节数组转换为 ByteArrayOutputStream 以便我可以在屏幕上显示它。

采纳答案by Josh M

byte[] bytes = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.write(bytes, 0, bytes.length);

Method description:

方法说明:

Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

将指定字节数组中的 len 个字节从偏移量 off 开始写入此字节数组输出流。

回答by Peter Lawrey

You can't display a ByteArrayOutputStream. What I suspect you are trying to do is

您无法显示 ByteArrayOutputStream。我怀疑你试图做的是

byte[] bytes = ...
String text = new String(bytes, "UTF-8"); // or some other encoding.
// display text.

You can make ByteArrayOutputStream do something similar but this is not obvious, efficient or best practice (as you cannot control the encoding used)

您可以让 ByteArrayOutputStream 做类似的事情,但这不是显而易见的、高效的或最佳实践(因为您无法控制所使用的编码)

回答by Naman

With JDK/11, you can make use of the writeBytes(byte b[])API which eventually calls the write(b, 0, b.length)as suggested in the answer by Josh.

使用JDK/11,您可以使用writeBytes(byte b[])最终调用Josh 回答中write(b, 0, b.length)建议的API 。

/**
 * Writes the complete contents of the specified byte array
 * to this {@code ByteArrayOutputStream}.
 *
 * @apiNote
 * This method is equivalent to {@link #write(byte[],int,int)
 * write(b, 0, b.length)}.
 *
 * @param   b     the data.
 * @throws  NullPointerException if {@code b} is {@code null}.
 * @since   11
 */
public void writeBytes(byte b[]) {
    write(b, 0, b.length);
}

The sample code would simply transform into --

示例代码将简单地转换为——

byte[] bytes = new byte[100];
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
baos.writeBytes(bytes);