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.
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 fileWarning that
getParentFile()
may returnnull
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 aboolean
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...