JavaException:(进程无法访问该文件,因为该文件被另一个进程使用)

在JavaFx中。 我试图导出表 – 查看内容使用Apache POI excel。所以,当我第一次点击button导出每一件事情都很好,并导出tableView的内容,当我想打开导出的文件.xls使用excel并尝试再次单击程序调用此exception:

Caused by: java.io.FileNotFoundException: example.xls ( (The process can not access the file because this file is used by another process)) at java.io.FileOutputStream.open0(Native Method) at java.io.FileOutputStream.open(FileOutputStream.java:270) at java.io.FileOutputStream.<init>(FileOutputStream.java:213) at java.io.FileOutputStream.<init>(FileOutputStream.java:162) at hmproject.MenuController.Print(MenuController.java:7985) ... 66 more 

这是我的代码:

  public void Print() throws JRException ,IOException,FileNotFoundException{ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet spreadsheet = workbook.createSheet("sample"); HSSFRow row = null; for (int i = 0; i < TousEmpView.getItems().size(); i++) { row = spreadsheet.createRow(i); for (int j = 0; j < TousEmpView.getColumns().size(); j++) { row.createCell(j).setCellValue(TousEmpView.getColumns().get(j).getCellData(i).toString()); } } File file=new File("example.xls"); if(file.canRead()) { FileOutputStream out = new FileOutputStream(file);//line of error workbook.write(out); out.close(); }else{ } } 

我明白这个例外,但是我的问题是:

如何确认文件是否被另一个进程使用或者没有?

我怎么能在FileOutputStream上做这个testing?

你不能真的,它通常是基于操作系统的。

您可以检查此链接了解更多信息java-check-if-file-is-already-open

为了避免这个问题,你可以在文件的名字中增加一个增量。 与时间有关的东西 System.currentTimeMillis的()。 所以你的文件将永远不会有相同的名称。 你当然会不时删除生成的文件

我find了答案, 检查文件是否已经打开

但这不是我想要的,所以我试图用我的需要修改它:

  public void Print() throws JRException, IOException, FileNotFoundException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet spreadsheet = workbook.createSheet("sample"); HSSFRow row = null; for (int i = 0; i < TousEmpView.getItems().size(); i++) { row = spreadsheet.createRow(i); for (int j = 0; j < TousEmpView.getColumns().size(); j++) { row.createCell(j).setCellValue(TousEmpView.getColumns().get(j).getCellData(i).toString()); } } File file = new File("example.xls"); File sameFileName = new File(file.getName()); if (!file.exists()||file.renameTo(sameFileName)) { System.out.println("file is closed"); FileOutputStream out = new FileOutputStream(file); workbook.write(out); out.close(); Desktop.getDesktop().open(file); } else { System.out.println("file is opened"); } }