TransformerHandler使用大型xml文件抛出OutOfMemoryError

时间:2015-09-01 09:47:48

标签: java xml sax

我正在使用SAXTransformerFactory来创建一个TransformerHandler来生成xml。 问题是,对于大量内容,我得到一个OutOfMemoryError。

发现内存中有很多类,包括

    oracle.xml.parser.v2.XMLElement
    char[]
    oracle.xml.parser.v2.XMLText
    oracle.xml.parser.v2.XMLAttr

即使在endDocument之后,这些类仍然存在。

简单示例

 public class Test
    {
         /**
          * test handler memory usage
          * @param loops no of loops - when large enogh - OutOfMemoryError !!!
      * @param xsltFilePath xslt file
      * @param targetXmlFile output xml file
      * @throws Exception
      */
     public static void testHandlerMemUsage(int loops, String xsltFilePath, String targetXmlFile)throws Exception
     {
          //verify SAX support
          TransformerFactory factory = TransformerFactory.newInstance();
          if(!factory.getFeature(SAXTransformerFactory.FEATURE))
               throw new UnsupportedOperationException("SAX tranformations not supported");
          TransformerHandler handler=
               ((SAXTransformerFactory)factory).newTransformerHandler(new StreamSource(xsltFilePath));
          handler.setResult(new StreamResult(targetXmlFile));

          handler.startDocument();
          handler.startElement(null,"root","root",new AttributesImpl());
          //loop
          for(int i=0;i<loops;i++)
          {
               handler.startElement(null,"el-"+i,"el-"+i,new AttributesImpl());
               handler.characters("value".toCharArray(),0,"value".length());
               handler.endElement(null,"el-"+i,"el-"+i);
          }
          handler.endElement(null,"root","root");
          //System.out.println("end document");
          //only after endDocument() starts to print..
          handler.endDocument();
          //System.out.println("ended document");
     }

     public static void main(String[] args)throws Exception
     {
          System.out.println("--starting..");
          testHandlerMemUsage(500000,"/copy.xslt","/testHandlerMemUsage.xml");
          System.out.println("--we are still here -- increase loops..");
     }
}

1 个答案:

答案 0 :(得分:0)

在调用-Xmx时使用java命令行参数来增加进程的堆大小,例如:

java -Xmx1g ...