gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:39:31 24 4
gpt4 key购买 nike

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

但令人惊讶的是,下面的代码读取的字节数总是比实际文件大小大 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() 的返回值它告诉读取并使用 len实际字节数相反。

关于java - 通过 FilterInputStream 计算的文件大小比实际大小高 12.5%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34495382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com