2017-09-02 53 views
1

在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上做這個測試?

回答

2

你不能真的,它通常是基於操作系統的。

您可以檢查此鏈接以獲取更多信息java-check-if-file-is-already-open

爲了避免這個問題,你可以在文件的名稱添加的增量。與時間有關的東西。 System.currentTimeMillis的()。所以你的文件將永遠不會有相同的名稱。您將有當然從時間生成的文件刪除時間

+0

我嘗試了你的建議,但我將有許多文件具有相同的內容。 –

+0

您必須實施一種不時刪除舊文件的方法。假設您檢查excel或libre office是否打開並關閉它。或者根據文件名稱中的時間刪除所有文件。並處理打開文件時可能發生的所有異常。您將能夠刪除所有舊文件,因爲用戶不會始終打開它們。您也可以使用異常處理來請求用戶關閉用於鎖定生成文件的程序。 –

+0

謝謝,我用你爲我建議的資源回答。 –

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

    } 
相關問題