Resource leak: workbook is never closed warning wh

2019-04-29 23:20发布

问题:

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

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?

回答1:

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.



回答2:

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

XSSFWorkbook workbook = new XSSFWorkbook(fIP)

// Do your stuff;

workbook.close();

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

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.



回答3:

Just change the example from apache page of:

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();
}