在TimerTask下循环POI读取Excel遇到了一个内存问题,正常情况下POI读取完Excel后方法结束内存也就回收了,但是放到TimerTask下,读取完这一次后内存并未回收,如下图所示;
现在有什么办法可以让这个循环定时任务执行的同时每次读取完后正常结束内存呢?
代码如下:
package com.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.zutil.Util;
public class test {
public static void main(String[] args) {
cronJob();
}
public static void cronJob() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Workbook wb = null;
Sheet sheet = null;
Row row = null;
String cellData = null;
String filepath = "Test.xlsx";
wb = readExcel(filepath);
if (wb != null) {
sheet = wb.getSheetAt(0);
int rownum = sheet.getPhysicalNumberOfRows();
row = sheet.getRow(0);
int colum = sheet.getPhysicalNumberOfRows();
for (int j = 1; j < rownum; j++) {
row = sheet.getRow(j);
if (row != null) {
for (int k = 0; k < colum; k++) {
cellData = (String) Util.getCellFormatValue(row.getCell(k));
}
} else {
break;
}
}
}
}
}, 0, 10 * 1000);
}
public static Workbook readExcel(String filePath) {
Workbook wb = null;
if (filePath == null) {
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
try {
is = new FileInputStream(filePath);
if (".xls".equals(extString) || ".XLS".equals(extString)) {
return wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(extString) || ".XLSX".equals(extString)) {
return wb = new XSSFWorkbook(is);
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return wb;
}
public static Object getCellFormatValue(Cell cell) {
Object cellValue = null;
DecimalFormat df = new DecimalFormat("#.#########");
if (cell != null) {
// 判断cell类型
switch (cell.getCellType()) {
// 数字
case Cell.CELL_TYPE_NUMERIC: {
cellValue = df.format(cell.getNumericCellValue());
break;
}
// 公式
case XSSFCell.CELL_TYPE_FORMULA: {
try {
cellValue = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}
break;
}
// 字符串
case HSSFCell.CELL_TYPE_STRING: {
cellValue = cell.getStringCellValue();
break;
}
// 空值
case HSSFCell.CELL_TYPE_BLANK: {
cellValue = "";
break;
}
default: {
cellValue = "";
break;
}
}
}
return cellValue;
}
}