繁体   English   中英

如何将Byte数组转换为ByteArrayOutputStream

[英]How to convert Byte array to ByteArrayOutputStream

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

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

方法描述:

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

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

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

您可以使ByteArrayOutputStream执行类似的操作,但这不是明显的,有效的或最佳实践(因为您无法控制所使用的编码)

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

/**
 * 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);
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM