java - Java/Selenium - 文件名、目录名或卷标语法不正确 (java.io.IOException)
问题描述
我编写了一个简单的 selenium 脚本来捕获屏幕截图,由于某种原因,这个脚本抛出了异常:
java.io.IOException:文件名、目录名或卷标语法不正确
public class ScreenshotUtil {
WebDriver driver;
public ScreenshotUtil(WebDriver driver) {
this.driver = driver;
}
public String getScreenShot(String fileName) {
SimpleDateFormat dFormat = new SimpleDateFormat("dd-MM-yyy HH-mm-ss");
Date date = new Date();
dFormat.format(date);
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String path = "./Screenshots/" + fileName + "_" + date + ".png";
File destination = new File(path);
try {
FileUtils.copyFile(source, destination);
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
}
解决方案
在 Windows 上使用 Unix 风格的路径。
更改当前路径分隔符/
以File.separator
实现代码的跨平台执行。
快速修复您的代码:
String path = "." + File.separator + "Screenshots" + File.separator + fileName + "_" + date + ".png";
推荐阅读
- cortex-m - 如何解决 Cortex-M4 中的 I2C 通信问题
- c# - 如何使用迁移向 Entity Framework Core 代码优先中的列添加描述?
- oracle - T-SQL 到 PL-SQL - 在同一搜索中使用 null 和 like,但只有空语句有效
- javascript - Javascript window.print() 函数在我的电子邮件模板中不起作用
- c++ - 如何将 std::find 用于类向量?
- android - 尚未执行转换在 docker 中使用颤振构建 android 应用程序
- java - 使用 Spring Security 对流程进行自定义授权
- c++ - 如何将具有自动返回类型的函数从头文件包含到多个 cpp 文件中
- reactjs - react-hook-form 和 Material-UI 的反应问题
- javascript - 使用 ngFor 和 ngIf 在数组中迭代两种不同的方式 - Angular