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

问题描述:

在JavaFx中。我试图用Apache POI导出表格查看内容到excel。好吧,当我第一次点击按钮导出时,每件事情都很好,并且tableView的内容被导出,并且当我想打开导出文件的.xls使用Excel和尝试再次单击该程序援引这一例外:JavaException:(进程无法访问文件,因为此文件被另一进程使用)

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上做这个测试?

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

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

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

+0

我尝试了你的建议,但我将有许多文件具有相同的内容。 –

+0

您必须实施一种不时删除旧文件的方法。假设您检查excel或libre office是否打开并关闭它。或者根据文件名称中的时间删除所有文件。并处理打开文件时可能发生的所有异常。您将能够删除所有旧文件,因为用户不会始终打开它们。您也可以使用异常处理来请求用户关闭用于锁定生成文件的程序。 –

+0

谢谢,我用你为我建议的资源回答。 –

我找到了答案,从Check if file is already open

但它不是我想要的究竟,所以我试图用我的需要对其进行修改:

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

    }