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

时间:2015-12-28 14:28:49

标签: java inputstream java-io

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

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

1 个答案:

答案 0 :(得分:1)

您忽略len的返回值,该值告诉实际读取的字节数并改为使用Dim r As Range Dim s As String s = "Hello World" Set r = Sheets(1).Range("A1:A15") r.Value = s