我有一个 Java Selenium 测试脚本,可以读取和写入 Excel 文件。问题是,如果文件已打开,则无法写入该文件。我希望我的脚本在写入文件之前自动关闭文件,以防用户忘记关闭 Excel 文件。
下面是打开 Excel 文件并从中读取数据的代码,即使文件已经打开,我也可以毫无问题地读取该文件
// prepare excel file
FileInputStream file = new FileInputStream(new
File(r.CONFIG.getProperty("testCaseFile")));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(6);
sheetmyWaitVar.until(ExpectedConditions.elementToBeClickable(By.id("ZipCodeEntry"))).sendKeys(sheet.getRow(row).getCell(2).getStringCellValue());
下面是写入 Excel 文件的代码。如果用户在运行脚本之前忘记关闭 Excel 文件,脚本将卡在此处。我正在尝试找到一种方法在此处添加代码,该代码将在执行下面的代码之前关闭文件
//write random first name to the same file
sheet.getRow(row).getCell(4).setCellValue(randomFirstName);
//write test result to the same file
sheet.getRow(row).getCell(25).setCellValue(testResult);
//write confirmation to the same file
sheet.getRow(row).getCell(23).setCellValue(confirmation); //write the confirmation number in the excel file
//write premium to the same file
sheet.getRow(row).getCell(24).setCellValue(premium); //write premium in the excel file
//enter timestamp
sheet.getRow(row).getCell(27).setCellValue(r.timeStamp());
//enter environment
sheet.getRow(row).getCell(26).setCellValue(r.CONFIG.getProperty("environment"));
FileOutputStream outFile =new FileOutputStream(new File(r.CONFIG.getProperty("testCaseFile")));
workbook.write(outFile);
outFile.close();
最佳答案
通常文件上的 writeLock 是独占的,因此为了获得它,文件上不应有其他锁(由操作系统处理)。 我认为没有办法以编程方式解决这个问题。
为什么不将内容写入新文件呢?
关于java - 如何在写入文件之前关闭selenium java中的excel文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29709574/