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

And*_*rio 3 java file filepath javax.imageio

我有以下代码:

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));
Run Code Online (Sandbox Code Playgroud)

现在,该路径C:\example\folder\不存在,因此我收到抛出异常并显示消息:(The system cannot find the path specified)

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

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

dka*_*zel 5

你必须自己创建丢失的目录

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

File outputFile = new File(nameAndPath);
outputFile.getParentFile().mkdirs();
ImageIO.write(image, "png", outputFile);
Run Code Online (Sandbox Code Playgroud)

getParentFile()如果输出文件是当前工作目录,则可能会返回警告null,具体取决于路径是什么以及您所在的操作系统,因此您应该在调用 mkdirs() 之前检查是否为空。

还有mkdirs()一种旧方法,如果出现问题,它不会抛出任何异常,而是返回booleanif success ,如果存在问题或目录已经存在,则可以返回 false ,所以如果你想彻底...

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