【问题标题】:Why did jdk 11 add writeBytes​(byte[] b) method to the ByteArrayOutputStream class while the write​(byte[] b) method did the same?为什么 jdk 11 在 ByteArrayOutputStream 类中添加了 writeBytes​(byte[] b) 方法,而 write​(byte[] b) 方法也是如此?
【发布时间】:2022-06-16 16:19:12
【问题描述】:

Oracle 自 JDK11 起在 ByteArrayOutputStream 类中增加了 writeBytes​(byte[] b) 方法。此方法接受一个字节数组并将其写入 ByteArrayOutputStream。但是 ByteArrayOutputStream 扩展了拥有 write​(byte[] b) 的 OutputStream 类来做同样的事情。为什么 java 需要一种新方法来做到这一点?

【问题讨论】:

    标签: java outputstream bytearrayoutputstream


    【解决方案1】:

    两种方法都将字节写入输出流。要先比较它们,我们应该查看它们的源代码:

    一方面,在 OutputStream 类中,我们有这 3 个嵌套方法来写入字节:

      public void write(byte b[]) throws IOException {
           write(b, 0, b.length);
      }
    
      public void write(byte b[], int off, int len) throws IOException {
         Objects.checkFromIndexSize(off, len, b.length);
         for (int i = 0 ; i < len ; i++) {
             write(b[off + i]);
         }
      }
      public abstract void write(int b) throws IOException;
    

    以上所有方法都会抛出 UncheckedException。

    另一方面,ByteArrayOutputStream 的 writesByte 方法调用此方法:

    public void writeBytes(byte b[]) {
         write(b, 0, b.length);
    }
    public synchronized void write(byte b[], int off, int len) {
        Objects.checkFromIndexSize(off, len, b.length);
        ensureCapacity(count + len);
        System.arraycopy(b, off, buf, count, len);
        count += len;
    }
    

    这些方法在写入字节之前检查字节数组的容量,因此它们摆脱了 UncheckedException。另外,write 方法是交易安全的,因为它是同步方法。

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 2018-01-09
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多