在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上做這個測試?
我嘗試了你的建議,但我將有許多文件具有相同的內容。 –
您必須實施一種不時刪除舊文件的方法。假設您檢查excel或libre office是否打開並關閉它。或者根據文件名稱中的時間刪除所有文件。並處理打開文件時可能發生的所有異常。您將能夠刪除所有舊文件,因爲用戶不會始終打開它們。您也可以使用異常處理來請求用戶關閉用於鎖定生成文件的程序。 –
謝謝,我用你爲我建議的資源回答。 –