Search code examples
javaxmlstax

Out of memory error in StAX


I am using the following simple StAX code to iterate through all the tags in XML. Size of input.xml > 100 MB

XMLInputFactory xif = XMLInputFactory.newInstance();
        FileInputStream in = new FileInputStream("input.xml");
        XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(in);

        xsr.next();
        while (xsr.hasNext()) {

            xsr.next();
            if(xsr.isStartElement() || xsr.isEndElement())
                 System.out.println(xsr.getLocalName());            
            }
        }

I am getting this error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Please tell me how to get around this. I read that StAX takes care of huge XMLs well, but I am getting the same error as DOM Parsers.


Solution

  • Define the Heap size while running the JVM

    -Xms    initial java heap size
    -Xmx    maximum java heap size
    -Xmn    the size of the heap for the young generation
    

    Example:

    bin/java.exe -Xmn100M -Xms500M -Xmx500M