gpt4 book ai didi

java - TransformerHandler 使用大型 xml 文件抛出 OutOfMemoryError

转载 作者:太空宇宙 更新时间:2023-11-04 13:29:31 25 4
gpt4 key购买 nike

我正在使用 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..");
}
}

最佳答案

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

java -Xmx1g ...

关于java - TransformerHandler 使用大型 xml 文件抛出 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32328462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com