微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Apche POI XWPFDocument 内存泄漏

如何解决Apche POI XWPFDocument 内存泄漏

我使用的是 Apache POI 5.0.0 版。我用它来创建 Word 文档并从中创建一个非常大的报告。 Apache POI 占用大量内存,创建报告后不释放内存。

我不想增加java堆空间,而是想在生成报告时刷新内存。我尝试使用 Visual VM 手动运行垃圾收集器,但它也没有清除内存。

以下是重现问题的代码

package com.mi6.word;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class CreateTable {

public static void main(String[] args) throws IOException,InterruptedException {
    
    XWPFDocument doc = new XWPFDocument();
    
    FileOutputStream out = new FileOutputStream(new File("createTable.docx"));
    
    int i = 0;
    
    while(i < 130000) {
        
        System.err.println("Table # "+ i);
        
        XWPFTable table = doc.createTable();
        
        XWPFTableRow row = table.getRow(0);
        row.getCell(0).setText("Row 0 Col 0");
        row.addNewTableCell().setText("Row 0 Col 1");
        row.addNewTableCell().setText("Row 0 Col 2");
        
        XWPFTableRow row2 = table.createRow();
        row2.getCell(0).setText("Row 1 Col 0");
        row2.getCell(1).setText("Row 1 Col 1");
        row2.getCell(2).setText("Row 1 Col 2");
        
        XWPFTableRow row3 = table.createRow();
        row3.getCell(0).setText("Row 2 Col 0");
        row3.getCell(1).setText("Row 2 Col 1");
        row3.getCell(2).setText("Row 2 Col 2"); 
        
        i++;
        
    }
    
    doc.write(out);
    
    doc.close();
    
    out.close();
    
    System.out.println("Create Table Write Successfully. ");
    
    //to keep alive the program to check memory is release or not. 
    while(true){
        Thread.sleep(1000);   
    }
    
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。