java.io.IOException : The filename, 目录名或卷标语法不正确

标签 java eclipse selenium-webdriver webpage-screenshot

我无法截图。我正在尝试将其保存在项目路径中,文件夹名称为 Screenshot

我尝试更改路径但仍然遇到相同的错误

public void getScreenShot() throws Exception {
        System.setProperty("webdriver.chrome.driver","C:\\Users\\abidk\\Desktop\\chromedriver.exe");    
        WebDriver driver= new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.google.com/");
        // store the webelement
        WebElement element_node = driver.findElement(By.xpath("//img[@id='hplogo']"));
        // pass the stored webelement to javascript executor
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("arguments[0].style.border='2px solid red'", element_node);
        Thread.sleep(1000);
         SimpleDateFormat dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
            Date date = new Date();
            File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, new File("./Screenshot/" + "Google" +  "-" +dateFormatter.format(date)+".png"));

    }

我想将文件保存在项目路径中并命名为ScreenShot

最佳答案

问题出在冒号“:”

Windows 不允许使用文件名中的 : 来保存文件。

使用dateFormatter.format(date).toString().replace(":", "-")

示例:

TakesScreenshot screenShotObj = ((TakesScreenshot) driver);
File sourceFile = screenShotObj.getScreenshotAs(OutputType.FILE);
Instant instant = Instant.now();
String toSavein="D:\\Screenshots";
String fileName = "ScreenShot" + instant.toString().replace(":", "-") + ".png";
File destinationFile = new File(toSavein, fileName);
FileUtils.copyFile(sourceFile, destinationFile);

结果: 截图2020-01-18T11-20-58.238372400Z.png

注意:Instant instant = Instant.now(); 仅在 Java 8 以上才允许

关于java.io.IOException : The filename, 目录名或卷标语法不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56420626/

相关文章:

java - 如何修复 'sessionFactory' 或 'hibernateTemplate' 是必需的问题

java - java 以降序打印文件内容

java - 在内部存储中创建文件夹

java - 使用 Java 测试登录时 Selenium 中的 NoSuchElementException

java - 将 JMS 监听器重新连接到 JBossMQ

java - 我想生成 'hash' 来识别给定的机器,如何在 Java 中做到这一点?

java - Eclipse Oxygen无法创建虚拟机

java - 在 Mac 上运行 Eclipse - 需要 JVM 版本 1.7 或更高版本

python - Python Selenium Web抓取返回找不到元素

python - 如何捕获高分辨率的网站截图?