这个问题已经在这里有了答案:
在此代码段中,我使用Apache POI库加载大小为10MB的Excel文件。 这将消耗近2GB的内存。 遍历所有行之后,我终于调用了close方法。 但是,似乎GC不能释放此流和对象占用的空间。 而且仍在使用2GB + 400MB的内存。
有任何想法吗?
这是我的代码:
public List loadFile(File excelFile) throws IOException, InvalidFormatException {
List allMeters = new ArrayList<>();
InputStream inputStream = new FileInputStream(excelFile);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet1 = workbook.getSheetAt(0);
Iterator rows_sheet1 = sheet1.iterator();
if (rows_sheet1.hasNext()) {
rows_sheet1.next(); //skip header
}
while (rows_sheet1.hasNext()) {
try {
Row currentRow = rows_sheet1.next();
Cell meterNoCell = currentRow.getCell(0);
Cell startPeriodCell = currentRow.getCell(1);
Cell endPeriodCell = currentRow.getCell(2);
Cell previousConsumption = currentRow.getCell(3);
Cell currentConsumption = currentRow.getCell(4);
Cell periodConsumptionCell = currentRow.getCell(5);
meterNoCell.setCellType(CellType.STRING);
startPeriodCell.setCellType(CellType.STRING);
endPeriodCell.setCellType(CellType.STRING);
//Reading values from above_defined cells and filling allMeters list (defined at the begining of the function).
//......
//Done
}
catch (Exception ex) {
Logger.getLogger(MetersList.class.getName()).log(Level.SEVERE, null, ex);
}
}
workbook.close();
inputStream.close();
return allMeters;
}