英文:
The process cannot access the file because it is being used by another process, while Renaming the Filepath?
问题
我为您翻译代码部分:
public class TestBase {
public static WebDriver driver;
public static Properties prop_config;
public static Properties prop_file_io;
public static String FilePath = "C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\PCPAutomation.xlsx"; // 在这里提供写入Excel表格的文件路径
public static String sheet_name = "PCP(P)";
public static String sheet_name1 = "PCP(S)";
@BeforeClass
public static void StartExecution() {
System.out.println("开始执行");
}
@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_file_io = new Properties();
prop_file_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 {
if (ITestResult.FAILURE == result.getStatus()) {
try {
TakesScreenshot screenshot = (TakesScreenshot) driver;
File src = screenshot.getScreenshotAs(OutputType.FILE);
Thread.sleep(5000);
FileUtils.copyFile(src, new File("./FailedTestCases/" + result.getName() + ".png"));
System.out.println("成功捕获屏幕截图");
} catch (Exception e) {
System.out.println("捕获屏幕截图时出现异常:" + e.getMessage());
}
}
driver.quit();
}
@AfterClass
public void EndExecution() throws Exception {
Path source = Paths.get("C:\\Users\\skumari1\\eclipse-workspace\\CoreLinkAutomation\\PCPAutomation.xlsx");
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);
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);
wb.write(new FileOutputStream(filePath));
}
请注意,上述代码只是翻译您提供的Java代码的一部分,不包括注释或其他内容。如果您需要进一步的帮助或有其他问题,请随时提出。
英文:
I am giving the same File path for writing data(Pass/Fail Test report) into Excel File and the Renaming same filepath with Current date and Time at the End of Execution, But while renaming the same Filepath with Current Date and Time at the End of Execution i am getting one Exception and that is: java.nio.file.FileSystemException: C:\Users\skumari1\eclipse-workspace\CoreLinkAutomation\PCPAutomation.xlsx -> C:\Users\skumari1\eclipse-workspace\CoreLinkAutomation\PCPAutomation1.xlsx + Validatedate(): The process cannot access the file because it is being used by another process.
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();
}
Here Created Method for Filepath and the Sheetname for writing data into excel sheet and Filepath i am providing in Base Class Before Execution you can check above in the code , Hence how do i close this program because wb.close is not working.
**If i am using Different Filepath then my code is working Fine, But Client Requirement is like Insert pass/Fail Test Report into Excel File and the same File should get Renamed as Updated Time Stamp at the end of Every Execution but when i am renaming it,i am getting this Exception,Can i get a Solution on this ? Is this possible to Rename the same Filepath which is in use already? **
答案1
得分: 1
你必须关闭你打开的文件。例如,new FileOutputStream(..)
打开一个文件用于写入。文件会一直保持打开状态,直到你关闭它。FileInputStream 也是一样的。
使用try-with-resources语句是一种方便的方式,在资源超出作用范围时自动关闭它们 - 例如:
try (OutputStream out = new FileOutputStream(filePath)) {
wb.write(out);
}
你还必须调用 wb.close()
以释放它所持有的系统资源。
英文:
You must close files that you open. For example, new FileOutputStream(..)
opens a file for writing. The file stays open until you close it. Same for FileInputStream.
The try-with-resources statement is a convenient way to automatically close resources when they go out of scope - for example:
try (OutputStream out = new FileOutputStream(filePath)) {
wb.write(out);
}
You must also call wb.close()
to free up system resources it holds.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论