如何让 ImageIO.write 根据需要创建文件夹路径

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

我有以下代码:

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));

现在,路径 C:\example\folder\ 不存在,所以我收到异常抛出消息:(The system cannot find the path specified)

如何让ImageIO自动创建路径,或者有什么方法可以自动创建路径?

在此代码的先前版本中,我使用 FileUtils.copyFile 来保存图像(以 File 对象的形式),这将自动创建路径。我怎样才能用这个复制它?我可以再次使用 FileUtils.copyFile,但我不知道如何将 BufferedImage 对象 "convert" 转换为 File 对象。

您必须自己创建缺少的目录

如果您不想使用第三方库,您可以在输出文件

目录中使用File.mkdirs()
File outputFile = new File(nameAndPath);
outputFile.getParentFile().mkdirs();
ImageIO.write(image, "png", outputFile);

警告 getParentFile() 可能 return null 如果输出文件是当前工作目录,这取决于路径是什么以及 OS 你所在的目录,所以你在调用 mkdirs() 之前真的应该检查 null。

此外,mkdirs() 是一种旧方法,如果出现问题,它不会抛出任何异常,而是 return 一个 boolean 如果成功,它可以 return false如果有问题或者目录已经存在那么如果你想彻底...

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

您可以通过在其父级上调用 File#mkdirs 来创建路径:

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();