Andrio Andrio - 3 months ago 18
Java Question

How to have ImageIO.write create a folder path as needed

I have the following code:

String nameAndPath = "C:\\example\\folder\\filename.png";

BufferedImage image = addInfoToScreenshot(); //this method works fine and returns a BufferedImage

ImageIO.write(image, "png", new File(nameAndPath));

Now, the path
does NOT exist, so I get an exception thrown with message:
(The system cannot find the path specified)

How can I have ImageIO create the path automatically, or what method can I use to create the path automatically?

In a previous version of this code, I used FileUtils.copyFile to save the image (which was in the form of a File object), and that would automatically create the path. How can I replicate that with this? I could use the FileUtils.copyFile again, but I don't know how I would "convert" the BufferedImage object into a File object.


you have to create the missing directories yourself

If you don't want to use a 3rd party library you can use File.mkdirs() on the parent directory of the output file

File outputFile = new File(nameAndPath);
ImageIO.write(image, "png", outputFile);

Warning that getParentFile() may return null if the output file is the current working directory depending on what the path is and what OS you are on so you should really check for null before calling mkdirs().

Also mkdirs() is an old method that doesn't throw any exceptions if there are problems, instead it returns a boolean if successful which can return false if either there's a problem OR if the directory already exists so if you want to be thorough...

 File parentDir = outputFile.getParentFile();
 if(parentDir !=null && ! parentDir.exists() ){
        throw new IOException("error creating directories");
 ImageIO.write(image, "png", outputFile);