有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    使用JDK/11,您可以使用writeBytes(byte b[])API,它最终会调用write(b, 0, b.length),正如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);
    }
    

    示例代码将简单地转换为

    byte[] bytes = new byte[100];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
    baos.writeBytes(bytes);
    
  2. # 2 楼答案

    无法显示ByteArrayOutputStream。我猜你想做的是

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

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

  3. # 3 楼答案

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

    方法说明:

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