Java:具有内存效率的 FastByteArrayOutputStream,minCapacity 大于 Integer 的最大大小,即 2147483647

问题描述 投票:0回答:0

FastByteArrayOutputStream 有一个写函数,它有 addBuffer,它接受整数的 minCapacity 并将下一个块大小分配为 minCapacity 的 2 的下一次幂。因此块大小不断增加以容纳缓冲区中的文件。 我有一个大于最大大小的文件,因此在将其写入缓冲区时,minCapacity 超过最大 Intger 值 2147483647 并开始以有符号整数 -2147483648 分配块大小,这是无效的。并给出附件中的例外情况。

有谁知道这个的解决方案。构造函数无济于事,因为函数只接受整数。

    /**
 * Create a new buffer and store it in the ArrayDeque.
 * <p>Adds a new buffer that can store at least {@code minCapacity} bytes.
 */
private void addBuffer(int minCapacity) {
    if (this.buffers.peekLast() != null) {
        this.alreadyBufferedSize += this.index;
        this.index = 0;
    }
    if (this.nextBlockSize < minCapacity) {
        this.nextBlockSize = nextPowerOf2(minCapacity);
    }
    this.buffers.add(new byte[this.nextBlockSize]);
    this.nextBlockSize *= 2;  // block size doubles each time
}

/**
 * Get the next power of 2 of a number (ex, the next power of 2 of 119 is 128).
 */
private static int nextPowerOf2(int val) {
    val--;
    val = (val >> 1) | val;
    val = (val >> 2) | val;
    val = (val >> 4) | val;
    val = (val >> 8) | val;
    val = (val >> 16) | val;
    val++;
    return val;
}
java fileoutputstream bytearrayoutputstream
© www.soinside.com 2019 - 2024. All rights reserved.