java.io.IOException:文件名,目录名称或卷标签语法不正确

时间:2019-06-03 02:51:45

标签: 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

1 个答案:

答案 0 :(得分:0)

问题出在冒号“:”

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);

结果: ScreenShot2020-01-18T11-20-58.238372400Z.png

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