【问题标题】:file size calculated via FilterInputStream is 12.5% higher than actual通过 FilterInputStream 计算的文件大小比实际大 12.5%
【发布时间】:2016-04-02 09:54:16
【问题描述】:

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

但令人惊讶的是,以下代码读取的字节数总是比实际文件大小大 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);
  }
}

【问题讨论】:

  • 为什么其中一种读取方法会忽略限制?
  • @Kayaman 因为 read(byte[] b) 方法只是调用 read(byte[] b, int off, int len) 方法

标签: java inputstream java-io


【解决方案1】:

您忽略了read() 的返回值,它告诉实际读取的字节数,并改用len

【讨论】:

  • 谢谢,它解决了我的问题,但我不明白为什么所有文件的读取字节数总是增加 12.5%。是否与缓冲区读取有关。
  • 可能是比本地缓冲区/数据包大小大 1/8 的缓冲区。
猜你喜欢
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多