使用docx4j进行docx比较时出现OutOfMemoryError

在我的应用程序中,我正在比较两个docx文件并创建一个html比较文件,当我尝试使用150或170行以下的文件然后没有问题,而我尝试比较像200行或更多的大文件然后那个时间显示了

java.lang.OutOfMemoryError: Java heap space error, 

任何人都可以帮忙吗?

由于您没有使用Docx4jDriver类,因此内存不足,这使得diff问题更容易通过首先执行段落级差异来处理。

像这样使用它:

  Body newerBody = ((Document)newerPackage.getMainDocumentPart().getJaxbElement()).getBody(); Body olderBody = ((Document)olderPackage.getMainDocumentPart().getJaxbElement()).getBody(); // 2. Do the differencing java.io.StringWriter sw = new java.io.StringWriter(); Docx4jDriver.diff( XmlUtils.marshaltoW3CDomDocument(newerBody).getDocumentElement(), XmlUtils.marshaltoW3CDomDocument(olderBody).getDocumentElement(), sw); // 3. Get the result String contentStr = sw.toString(); System.out.println("Result: \n\n " + contentStr); Body newBody = (Body) org.docx4j.XmlUtils .unmarshalString(contentStr); 

您可以使用-Xmx和-Xmx将堆空间设置为VM Arguments

这里有更多关于堆大小调整或这里的堆大小

尝试使用命令行参数-Xmx-Xms来增加Java堆大小。

同样在您的代码中,使用以下内容测试您实际上已增加堆大小:

 long heapSize = Runtime.getRuntime().totalMemory(); System.out.println("Heap Size = " + heapSize); 

在第117行调用Differencer.diff之前执行此操作。

尝试分析您的应用程序,而不是做出假设或智能猜测。 您可以使用随Jdk一起提供的visualvm或控制台。

此外,您可以使用jmap对应用程序进行堆转储,然后使用jhat或eclipse mat(我更喜欢这个,google it)来查看消耗内存的内容并注意任何exception行为。