关闭BufferedImage,以便删除它?

时间:2018-01-27 11:50:32

标签: java

我使用ImageIO.read(File file)函数打开了一个图像,它返回了BufferedImage。我从该图像中读取像素,现在我想从文件系统中删除它。问题是file.delete()会返回false。调用Files.delete(file.toPath())会引发异常:

java.nio.file.FileSystemException: C:\<file_location>\1517053169520.png: The process cannot access the file because it is being used by another process.

为了便于阅读,我缩短了路径。

以下是代码段:

public void test (File file) {
    BufferedImage image = ImageIO.read(file);
    byte[] pixels = ((DataBufferByte)image.getRaster().getDataBuffer()).getData();
    // I do a bunch of things here, but I don't modify the pixels
    image.flush();

    /* I tried this too, but I know that GC doesn't have to be called immediately when I make a call to System.gc()

    image = null;
    System.gc();

    */

    Files.delete(file.toPath());
}

所以,我的问题是:如何释放文件,以便删除?

2 个答案:

答案 0 :(得分:2)

有一个issue reported some time ago with a similar scenario。以下代码段应该通过释放流来解决问题:

BufferedImage image = null;
InputStream stream = null;
try {
    stream = new FileInputStream(file);
    image = ImageIO.read(stream);

} catch (Exception ex) {
    log.error("Image could not be read: "+file);

} finally {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException ex) {
            log.error("ERROR closing image input stream: "+ex.getMessage(), ex);
        }
    }
}

答案 1 :(得分:2)

@kekec展示了使用过时的构造实现的好主意。从Java7开始,您可以使用try-with-resources来简化上面的代码(下面,谁知道):

BufferedImage image = null;
try(FileInputStream stream = new FileInputStream(file)){
    image = ImageIO.read(stream);
}

当然,您可以决定捕捉异常,或让它向外抛出。