【发布时间】: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