在JavaFx中。我正在尝试使用Apache POI将表格视图内容导出到excel。好吧,当我第一次点击按钮导出时,每件事都运行良好且内容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上进行此测试?
答案 0 :(得分:3)
你不能真的,它通常是基于操作系统的。
您可以查看此链接以获取更多信息java-check-if-file-is-already-open
要避免此问题,您可以在文件名中添加增量。与时间有关的东西。 System.currentTimeMillis的()。所以你的文件永远不会有相同的名字。您当然会不时删除生成的文件
答案 1 :(得分:1)
但这不是我想要的,所以我试图用我的需要修改它:
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");
}
}