java 资源泄漏:使用 Apache.POI XSSFWorkbook 时工作簿从未关闭警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31830970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:12:18  来源:igfitidea点击:

Resource leak: workbook is never closed warning when using Apache.POI XSSFWorkbook

javagarbage-collectionapache-poi

提问by rpd

So, I using Apache POI in order to parse an Excel file to my Database. For this I am initializing an XSSFWorkbookas follows:

因此,我使用 Apache POI 将 Excel 文件解析到我的数据库。为此,我正在初始化XSSFWorkbook如下:

XSSFWorkbook workbook = new XSSFWorkbook(fIP);

Then I proceed with my method. workbook.close()is not available as a method to close the workbook afterwards. Any ideas of how can I let garbage collection take the workbook after the task is finished?

然后我继续我的方法。workbook.close()不能用作事后关闭工作簿的方法。关于如何在任务完成后让垃圾收集处理工作簿的任何想法?

回答by IanB

I had this issue, and it was making little sense. In the end I tracked the issue down to my IDE (netbeans) was picking up an earlier version of the POI libraries (v3.8) which didn't have the "close" method. So check your class path and look for duplicate imports of different versions of the POI libraries.

我遇到了这个问题,这没什么意义。最后,我将问题追溯到我的 IDE (netbeans) 选择了没有“关闭”方法的早期版本的 POI 库 (v3.8)。因此,请检查您的类路径并查找不同版本的 POI 库的重复导入。

回答by stevecross

The docssay that the class implements Closeable. Thus it has a close()method and you can close the workbook like this:

文档说,类实现Closeable。因此它有一个close()方法,您可以像这样关闭工作簿:

XSSFWorkbook workbook = new XSSFWorkbook(fIP)

// Do your stuff;

workbook.close();

Since the class also implements AutoCloseableyoun can go with a try-with-resources block as well:

由于该类还实现了您也AutoCloseable可以使用 try-with-resources 块:

try (XSSFWorkbook workbook = new XSSFWorkbook(fIP)) {
    // Do your stuff
}

If you use this approach the workbook will be closed automatically after the try block has finished.

如果您使用这种方法,工作簿将在 try 块完成后自动关闭。

回答by nakani

Just change the example from apache page of:

只需从 apache 页面更改示例:

try {
    FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
    Workbook workbook = new XSSFWorkbook(excelFile);
    //more stuffs
}

To:

到:

Workbook workbook;
try {
    InputStream excelFile = file.getInputStream();
    workbook = new XSSFWorkbook(excelFile);
    //more stuffs

    workbook.close();
    excelFile.close();
}