Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close BufferedImage so I can delete it?

Tags:

java

I have opened an image using ImageIO.read(File file) function and it returned the BufferedImage. I read the pixels from that image, and now I want to delete it from file system. The problem is that file.delete() returns false. Call to the Files.delete(file.toPath()) throws an exception:

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

I've shortened the path for the sake of readability.

Here's the code snippet:

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());
}

So, my question is: How can I release the file, so that it can be deleted?

like image 685
Bartic Avatar asked Mar 17 '26 04:03

Bartic


2 Answers

There was an issue reported some time ago with a similar scenario. The following snippet should solve the issue by releasing the stream:

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);
        }
    }
}
like image 61
sashimi Avatar answered Mar 18 '26 17:03

sashimi


@kekec shows the good idea implemented with an obsolete construct. Starting with Java7 you can use try-with-resources which simplifies the code above (below, who knows) to:

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

And of course you can decide to catch the Exception, or let it get thrown outwards.

like image 24
tevemadar Avatar answered Mar 18 '26 16:03

tevemadar