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

8.7k views Asked by At

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 C:\example\folder\ 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.

2

There are 2 answers

1
dkatzel On BEST ANSWER

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);
outputFile.getParentFile().mkdirs();
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() ){
    if(!parentDir.mkdirs()){
        throw new IOException("error creating directories");
    }
 }
 ImageIO.write(image, "png", outputFile);
0
nanofarad On

You can create the path by calling File#mkdirs on its parent:

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories...

File child = new File("C:\\example\\folder\\filename.png");
new File(child.getParent()).mkdirs();