Osiris
Osiris

Reputation: 4185

Getting a java.io.FileNotFoundException (Access is denied)

I'm using the following code to save a BufferedImage to disk:

savePath = new File(path);
savePath.mkdirs();
savePath.createNewFile();
javax.imageio.ImageIO.write(img, "png", savePath);

This particular piece of code is executed off a server, and is run about 10 times for every client request. Most of the time (9 requests out of 10), it works fine, and the image is saved to disk as expected.

However, sometimes I get a java.io.FileNotFoundException (Access is denied) on the ...ImageIO.write() line, and the image is not saved. (The folder is still created)

What can cause the exception?

Upvotes: 0

Views: 2271

Answers (1)

user207421
user207421

Reputation: 310840

It's hard to believe this actually works. You are creating savePath as a directory, by calling mkdirs(), and then trying to create it as a file. You need to call savePath.getParentFile().mkdirs() instead.

The createNewFile() call is redundant.

Upvotes: 4

Related Questions