通过 FilterInputStream 计算的文件大小比实际高 12.5%

file size calculated via FilterInputStream is 12.5% higher than actual

我正在尝试通过以下 class 限制上传到我的应用程序的文件大小。 我正在读取输入流并在文件大小超过限制时抛出异常。

但令人惊讶的是,下面代码读取的字节数总是比实际文件大小大 12.5%。我已经为多个文件试过了。

尝试用谷歌搜索,但找不到任何满意的答复。

这有什么具体原因吗?如果是那么如何纠正?

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.exceptions.SomeErrorCode;
import com.exceptions.SomeFileSizeException;
import com.logger.MyLogger;

/**
 * InputStream that guards the maxim number of bytes to allow to be read. It throws an IOException if the size is exceeded.
 */
public class SizeLimitedInputStream extends FilterInputStream {

  private long maxSize = 0;
  private long currentSize = 0;

  public SizeLimitedInputStream(InputStream in, long maxSize) {
    super(in);
    this.maxSize = maxSize;
  }

  private void checkLimit(long size) throws SomeFileSizeException {
    currentSize += size;
    if (currentSize > maxSize) {
      throw new SomeFileSizeException(SomeErrorCode.FILE_SIZE_TOO_LONG, "File Size cannot exceed " + maxSize + " bytes.");
    }
  }

  public long getMaxSize() {
    return maxSize;
  }

  @Override
  public int read() throws IOException, SomeFileSizeException {
    checkLimit(1);
    return super.read();
  }

  @Override
  public int read(byte[] b) throws IOException, SomeFileSizeException {
    return super.read(b);
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException, SomeFileSizeException {
    checkLimit(len);
    return super.read(b, off, len);
  }
}

您忽略了 read() 的 return 值,该值告诉 实际 读取的字节数并使用 len 代替。