首页 > 解决方案 > 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;
    }
}

标签: javaseleniumselenium-webdriver

解决方案


在 Windows 上使用 Unix 风格的路径。

更改当前路径分隔符/File.separator实现代码的跨平台执行。

快速修复您的代码:

String path = "." + File.separator + "Screenshots" + File.separator + fileName + "_" + date + ".png";

推荐阅读