我可以在Java中正确关闭输入流吗? [英] Am I closing my input stream correctly in Java?
问题描述
我创建了一个扩展InputStream的类,以便我可以对正在读取的字节数进行计数,并在超出我定义的最大限制时引发异常。
I created a class that extends InputStream so that I can keep count of the number of bytes being read and throw an exception if it exceeds a max limit that I define.
这是我的课程:
public class LimitedSizeInputStream extends InputStream
{
private final InputStream original;
private final long maxSize;
private long total;
public LimitedSizeInputStream(InputStream original, long maxSize)
{
this.original = original;
this.maxSize = maxSize;
}
@Override
public int read() throws IOException
{
int i = original.read();
if (i >= 0)
{
incrementCounter(1);
}
return i;
}
@Override
public int read(byte b[]) throws IOException
{
return read(b, 0, b.length);
}
@Override
public int read(byte b[], int off, int len) throws IOException
{
int i = original.read(b, off, len);
if (i >= 0)
{
incrementCounter(i);
}
return i;
}
private void incrementCounter(int size) throws IOException
{
total += size;
if (total > maxSize)
{
throw new IOException("InputStream exceeded maximum size in bytes.");
}
}
}
这是来自:< a href = https://stackoverflow.com/questions/15445504/copy-inputstream-abort-operation-if-size-exceeds-limit/30072143#30072143>复制InputStream,如果大小超出限制,则中止操作 ,我正在实现一个Jersey API,如果用户上传的文件过大,该API将会失败。
This is coming from: Copy InputStream, abort operation if size exceeds limit, I am implementing a Jersey API that needs to fail if a user is uploading a file that is too large.
这是我的资源类:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/test")
public Response load(
@Context HttpServletRequest request,
@FormDataParam(FILE_FIELD) FormDataBodyPart file)
{
if (request.getContentLength() > MAX_FILE_SIZE_IN_BYTES)
{
// fail fast handle failure
}
try (InputStream stream = new LimitedSizeInputStream(
file.getValueAs(InputStream.class), MAX_FILE_SIZE_IN_BYTES))
{
// some logic
}
catch (IOException e)
{
// handle failure
}
}
我将LimitedSizeInputStream包装在try资源中,因此我认为流应该正确关闭。对于是否正确处理关闭操作,或者我是否通过LimitedSizeInputStream和file.getValueAs(InputStream.class)技术上打开两个输入流,而只有一个正在关闭,我只是感到困惑?
I wrapped LimitedSizeInputStream in my try resource so I think the stream should close properly. I'm just a bit confused as to whether the close is handled correctly or if I'm technically opening two input streams through LimitedSizeInputStream and file.getValueAs(InputStream.class) and only one is closing?
推荐答案
try-with-resources仅关闭声明的资源。因此只会关闭 metadataStream
。
The try-with-resources only closes the declared resource. So will only close metadataStream
.
您应在 LimitedSizeInputStream
中实现 close
方法关闭原始流。
You should implement the close
method in LimitedSizeInputStream
to close the original stream.
@Override
public void close() throws IOException {
original.close();
}
这篇关于我可以在Java中正确关闭输入流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!