java - How to have ImageIO.write create a folder path as needed -
i have following code:
string nameandpath = "c:\\example\\folder\\filename.png"; bufferedimage image = addinfotoscreenshot(); //this method works fine , returns bufferedimage imageio.write(image, "png", new file(nameandpath)); now, path c:\example\folder\ not exist, exception thrown message: (the system cannot find path specified)
how can have imageio create path automatically, or method can use create path automatically?
in previous version of code, used fileutils.copyfile save image (which in form of file object), , automatically create path. how can replicate this? use fileutils.copyfile again, don't know how "convert" bufferedimage object file object.
you have create missing directories yourself
if don't want use 3rd party library can use file.mkdirs() on parent directory of output file
file outputfile = new file(nameandpath); outputfile.getparentfile().mkdirs(); imageio.write(image, "png", outputfile); warning getparentfile() may return null if output file current working directory depending on path , os on should check null before calling mkdirs().
also mkdirs() old method doesn't throw exceptions if there problems, instead returns boolean if successful can return false if either there's problem or if directory exists if want thorough...
file parentdir = outputfile.getparentfile(); if(parentdir !=null && ! parentdir.exists() ){ if(!parentdir.mkdirs()){ throw new ioexception("error creating directories"); } } imageio.write(image, "png", outputfile);
Comments
Post a Comment