如何检查ImageInputStream是否已经关闭?

问题描述 投票:1回答:2

在我目前的项目中,我使用了操纵图像的第三方库。在某些情况下,我不知道ImageInputStream来自哪里(该库的源代码是专有的,我无法编辑该代码)。但我需要关闭每一个流,以便释放资源,无论其来源如何。

javax.imageio.stream.ImageInputStream #close方法在流已经关闭时抛出异常。

我知道((MemoryCacheImageInputStream) ios).isClosed()技巧。但该方法具有私有访问级别并强制执行令人讨厌的转换。

我也知道另一种方法:捕获IOException,检查消息并禁止异常(当它与关闭有关时)或重新抛出它(否则),如下所示:

try {
    imageInputStream.close();
} catch (IOException onClose) {
    String message = onClose.getMessage();
    if ("closed".equals(message)) {
        // suppress the exception and write to log
    } else {
        throw new IllegalStateException(onClose);
    }
}

有没有一种优雅的方式来检查ImageInputStream的状态?

java javax.imageio
2个回答
1
投票

您实际上不需要检查流的状态,只需要确保它不会多次关闭。一种选择是将ImageInputStream包装在另一个类中,在流已经关闭的情况下,将close()重写为no-op。关于这个的好处是,它将与try-with-resources很好地协同工作,如下所示:

try (ImageInputStream stream = new CloseableStreamFix(ImageIO.createImageInputStream(input))) {
    stream.close(); // Close stream once (or as many times you want)
}
// stream implicitly closed again by automatic resource handling, no exception

不幸的是,CloseableStreamFix的代码是非常重要的,所以我不确定它是否算作“优雅”(尽管用法是这样):

final class CloseableStreamFix extends ImageInputStreamImpl {

    private boolean closed;
    private final ImageInputStream delegate;

    public CloseableStreamFix(ImageInputStream delegate) {
        this.delegate = delegate;
    }

    // The method you actually want to override.
    @Override
    public void close() throws IOException {
        if (!closed) {
            closed = true;

            super.close();
            delegate.close();
        }
    }

    // You have to implement these abstract read methods. Easy, just delegate them.
    // ...except you need to keep the stream position in sync.
    @Override
    public int read() throws IOException {
        streamPos++;
        return delegate.read();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int read = delegate.read(b, off, len);

        if (read > 0) {
            streamPos += read;
        }

        return read;
    }

    // In a perfect world, the above should be all you need to do. Unfortunately, it's not.


    // We need to keep the delegate position in sync with the position in this class.
    // Overriding the seek method should do.
    @Override
    public void seek(long pos) throws IOException {
        super.seek(pos); // Don't forget to call super here, as we rely on positions being in sync.
        delegate.seek(pos);
    }

    // Some plugins require stream length, so we need to delegate that.
    @Override
    public long length() {
        try {
            // Unfortunately, this method does not declare IOException like the
            // interface method does, so we need this strange try/catch here.
            return delegate.length();
        } catch (IOException e) {
            // It's also possible to use a generics hack to throw a checked
            // exception as unchecked. I leave that as an exercise...
            throw new UndeclaredThrowableException(e);
        }
    }

    // You may be able to skip the flush methods. If you do, skip both.
    @Override
    public void flushBefore(long pos) throws IOException {
        delegate.flushBefore(pos);
    }

    @Override
    public long getFlushedPosition() {
        return delegate.getFlushedPosition();
    }

    // You could probably skip the methods below, as I don't think they are ever used as intended.
    @Override
    public boolean isCached() {
        return delegate.isCached();
    }

    @Override
    public boolean isCachedMemory() {
        return delegate.isCachedMemory();
    }

    @Override
    public boolean isCachedFile() {
        return delegate.isCachedFile();
    }
}

...虽然我认为上述内容涵盖了所有基础,但你应该测试一下。

除非你打算使用大量的try-with-resources语句,否则你可能会发现一个简单的try / catch(就像你已经拥有的)更具可读性。我会提取它作为这样的方法,但是:

static void close(Closeable closeable) throws IOException {
    try {
        closeable.close();
    }
    catch (IOException e) {
        if (!"closed".equals(e.getMessage())) {
            throw e;
        }
        // Otherwise, we're already closed, just ignore it,
    }
}

请注意,如果有人决定需要更好的解释,依赖这样的异常消息可能会在未来的Java版本中破坏...


1
投票

一种方法是创建一个扩展ImageInputStream并实现自己的isClosed()方法的类,例如通过重写close()方法,在关闭时将布尔标志设置为true。

© www.soinside.com 2019 - 2024. All rights reserved.