0

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?

2
  • If you are using a Uinix related OS it might be an issue of permissions. Is the path of the image when it works the same as when it fails? Commented Nov 9, 2012 at 5:47
  • It's Windows. Write permissions aren't a problem. And the path is always of the form [constant_path]/[random number]/imagename.png Commented Nov 9, 2012 at 5:49

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked. I was under the impression that mkdirs() creates all dirs required for the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.