4

Below is the sample code snippet to create SXSSFWorkbook:

try(SXSSFWorkbook wb = new SXSSFWorkbook()) {
    //...
} finally {
    wb.dispose(); //wb not accessible over here, so can't use try with resource
}

Here problem is that if I use try with resource then can't dispose() SXSSFWorkbook in finally, as variable wb won't be accessible in finally block.

I wanted know that is disposing of workbook necessary to delete temporary files or since SXSSFWorkbook is AutoCloseable, try with resource will take care of it.

4

2 回答 2

6

不确定apache poi程序员中是否有人会回答这个问题。但是apache poi是开源的。所以每个程序员都可以通过查看代码自己回答这个问题。

状态 2018 年 5 月,apache poi版本3.17

SXSSFWorkbook.java

public class SXSSFWorkbook implements Workbook

那么为什么这可以成为在资源中使用的资源呢?因为

工作簿.java

public interface Workbook extends Closeable, Iterable<Sheet>

所以org.apache.poi.ss.usermodel.Workbookextendsjava.io.Closeable等实现这个的类必须提供一个方法 close

SXSSFWorkbook.close

如您所见,单SheetDataWriters 将被关闭,然后内部XSSFWorkbook _wb将被关闭。

SheetDataWriter.close

SheetDataWriter.close仅刷新并关闭Writer _out.

所以不,dispose直到现在(2018 年 5 月)在apache poi版本中自动关闭时都没有调用3.17

并且只有SheetDataWriter.dispose会删除TempFile _fd为每个工作表创建的。

于 2018-05-16T05:47:12.673 回答
1

这是问题的正式解决方案。

SXSSFWorkbook t_wb = null;
try(SXSSFWorkbook wb = t_wb = new SXSSFWorkbook()) {
    //...
} finally {
    if(t_wb != null) t_wb.dispose();
}
于 2019-07-30T17:44:22.307 回答