You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决java.nio.file.FileSystemException:文件被其他进程占用问题

解决Java截图代码中的java.nio.file.FileSystemException异常

问题根源

  • 目标目录Screenshots未提前创建:FileUtils.copyFile不会自动递归创建父目录,当指定路径的目录不存在时,会触发文件系统异常
  • 冗余的本地文件操作:原代码先将截图保存到本地,再读取转Base64,多此一举的文件IO增加了异常风险

修复方案1:补全目录创建逻辑

修改代码,提前检查并创建目标文件的父目录:

public String getScreenShotAsBase64() throws IOException {
    File source = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    String path = System.getProperty("user.dir") + "/Screenshots/image.png";
    File targetFile = new File(path);
    // 递归创建所有不存在的父目录
    if (!targetFile.getParentFile().exists()) {
        targetFile.getParentFile().mkdirs();
    }
    FileUtils.copyFile(source, targetFile);
    byte[] imageBytes = IOUtils.toByteArray(new FileInputStream(targetFile));
    return Base64.getEncoder().encodeToString(imageBytes);
}

修复方案2:跳过本地文件存储(更优)

直接将截图转为字节数组生成Base64,彻底避开文件系统操作:

public String getScreenShotAsBase64() throws IOException {
    // 直接获取截图字节数组,无需落地到本地文件
    byte[] screenshotBytes = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
    return Base64.getEncoder().encodeToString(screenshotBytes);
}

额外异常排查点

如果异常仍存在,可能是文件被占用,可通过生成唯一文件名避免冲突:

// 用时间戳生成唯一文件名
String timestamp = String.valueOf(System.currentTimeMillis());
String path = System.getProperty("user.dir") + "/Screenshots/image_" + timestamp + ".png";

内容的提问来源于stack exchange,提问作者derren dhanraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:10:49