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?
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);
}
}
}
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With