如何解决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
相关产品推荐
相关产品推荐

