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

3

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

现在,路径C:\example\folder\不存在,因此我会收到一个异常抛出消息:(系统找不到指定的路径) 我该如何让ImageIO自动创建路径,或者有什么方法可以自动创建路径?
在此代码的早期版本中,我使用FileUtils.copyFile保存图像(以File对象的形式),这将自动创建路径。我该如何复制这个过程?我可以再次使用FileUtils.copyFile,但我不知道如何将BufferedImage对象“转换”为File对象。
2个回答

5

你需要自己创建缺失的目录。

如果你不想使用第三方库,可以在输出文件的父目录上使用File.mkdirs()方法。

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

警告:如果输出文件是当前工作目录,则根据路径和操作系统的不同,getParentFile()可能返回null,因此在调用mkdirs()之前应该确实检查是否为null。

mkdirs()也是一个旧方法,如果有问题,它不会抛出任何异常,而是返回一个boolean,如果成功,可以返回false(如果存在问题或目录已经存在),因此如果您想要更全面地处理问题...

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

太好了,我刚刚添加了一些额外的错误检查,你也应该这样做。 - dkatzel

0

你可以通过调用父目录的File#mkdirs方法来创建路径:

创建由此抽象路径名指定的目录,包括任何必要但不存在的父目录...

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接