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

JavaException : (The process can not access the file because this file is used by another process)

在 JavaFx 中。我正在尝试使用 Apache POI 将 table-View 内容导出到 excel。好吧,当我第一次单击按钮 Export 时一切正常, tableView 的内容被导出,当我想使用 excel 打开导出的文件 .xls 并尝试再次单击程序调用此异常:

    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 上进行此测试?

你真的不能,它通常是基于 OS 的。

您可以查看此 link 了解更多信息 java-check-if-file-is-already-open

为避免此问题,您可以在文件名中添加增量。与时代有关的东西。 System.currentTimeMillis()。所以你的文件永远不会有相同的名字。您当然需要不时删除生成的文件

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

    }