首页 > 解决方案 > 该进程无法访问该文件,因为它正在被另一个进程使用,同时重命名文件路径?

问题描述

我提供了相同的文件路径,用于将数据(通过/失败测试报告)写入 Excel 文件,并在执行结束时使用当前日期和时间重命名相同的文件路径,但是在最后使用当前日期和时间重命名相同的文件路径执行我得到一个异常,即: java.nio.file.FileSystemException: C:\Users\skumari1\eclipse-workspace\CoreLinkAutomation\PCPAutomation.xlsx -> C:\Users\skumari1\eclipse-workspace\CoreLinkAutomation\ PCPAutomation1.xlsx + Validatedate():进程无法访问该文件,因为它正被另一个进程使用。

public class TestBase {
        public static WebDriver driver;
        public static Properties prop_config;
        public static Properties prop_filr_io; 
        
        public static String FilePath="C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\PCPAutomation.xlsx"; **Here i am providing the filepath to write data into Excel sheet.**

        public static String sheet_name="PCP(P)";
        public static String sheet_name1="PCP(S)";
        
           
      @BeforeClass
    public static void StartExecution()
    {
        System.out.println("Start Execution");
        
    }
    
        
        
        @BeforeMethod
        public static void initialization() throws IOException
        {
            try {
                prop_config=new Properties();
                prop_config.load(new FileInputStream("C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\src\\main\\java\\com\\corelink\\resources\\config.properties"));
                String browserName=prop_config.getProperty("browser");
    
                if(browserName.equals("chrome"))
                {
                    System.setProperty("webdriver.chrome.driver","H:\\udemy\\chromedriver_win32 (1)\\chromedriver.exe");
                    driver=new ChromeDriver();
                }
                else if(browserName.equals("FF"))
                {
                    System.setProperty("webdriver.gecko.driver","C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\geckodriver.exe");
                    driver=new FirefoxDriver();
                }
                
                driver.manage().window().maximize();
                driver.manage().deleteAllCookies();
                driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
                driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
                driver.get(prop_config.getProperty("url"));
                prop_filr_io=new Properties();
                prop_filr_io.load(new FileInputStream("C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\src\\main\\java\\com\\corelink\\resources\\file_constants.properties"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            
            
    
            
            
        }
        @AfterMethod
        public void screenShot(ITestResult result) throws Exception{
             //using ITestResult.FAILURE is equals to result.getStatus then it enter into if condition
             if(ITestResult.FAILURE==result.getStatus()){
             try{
             // To create reference of TakesScreenshot
             TakesScreenshot screenshot=(TakesScreenshot)driver;
             // Call method to capture screenshot
             File src=screenshot.getScreenshotAs(OutputType.FILE);
             // Copy files to specific location 
             // result.getName() will return name of test case so that screenshot name will be same as test case name
             //FileUtils.cleanDirectory(new File("./FailedTestCases"+result.getName()+".png"));
             Thread.sleep(5000);
             FileUtils.copyFile(src, new File("./FailedTestCases/" +result.getName()+".png"));
             System.out.println("Successfully captured a screenshot");
    
             }catch (Exception e){
             System.out.println("Exception while taking screenshot "+e.getMessage());
             } 
             }
            
             driver.quit();
             }
        
        @AfterClass
        
            public void EndExecution() throws Exception{
            
            
            
        
            Path source = Paths.get("C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\PCPAutomation.xlsx");**The same Filepath using here**
    
            try{
    
                Files.move(source, source.resolveSibling("PCPAutomation1.xlsx + Validatedate()"),
                          StandardCopyOption.REPLACE_EXISTING);
    
            } catch (Exception e) {
              e.printStackTrace();
            }
            
            }
        public static String Validatedate() {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy_HH_mm_ss");
            Date date = new Date();
            String date1= dateFormat.format(date);
            // System.out.println("Current date and time is " +date1);
             return date1;
    }
    }


public static void write_test_result(String result, String sheet_name, String filePath,int row_num,int col_num) throws EncryptedDocumentException, FileNotFoundException, IOException
    {
        
        Workbook wb = WorkbookFactory.create(new FileInputStream(filePath));
        Sheet sh = wb.getSheet(sheet_name);
        
        sh.getRow(row_num).createCell(col_num).setCellValue(result);
        //sh.createRow(row_num).createCell(col_num).setCellValue(result);
        wb.write(new FileOutputStream(filePath));
        //wb.close();

    
            }

这里 Created Method for Filepath 和 Sheetname 用于将数据写入 Excel 工作表和 Filepath 我在基类中提供 执行之前你可以在代码中检查上面,因此我如何关闭这个程序,因为 wb.close 不起作用。

**如果我使用不同的文件路径,那么我的代码工作正常,但客户要求就像将通过/失败测试报告插入 Excel 文件,并且相同的文件应该在每次执行结束时重命名为更新的时间戳但是当我重命名它,我得到这个异常,我能得到一个解决方案吗?这是否可以重命名已经使用的相同文件路径?**

标签: javaselenium-webdriver

解决方案


必须关闭您打开的文件。例如,new FileOutputStream(..)打开一个文件进行写入。该文件保持打开状态,直到您关闭它。FileInputStream 也一样。

try-with-resources 语句是一种在超出范围时自动关闭资源的便捷方式 - 例如:

try (OutputStream out = new FileOutputStream(filePath)) {
    wb.write(out);
}

您还必须调用wb.close()以释放它所拥有的系统资源。


推荐阅读