How to convert Byte array to ByteArrayOutputStream

蹲街弑〆低调 提交于 2019-12-10 01:04:54

问题


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


回答1:


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.




回答2:


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

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)




回答3:


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.

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


来源:https://stackoverflow.com/questions/18575480/how-to-convert-byte-array-to-bytearrayoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!