I am parsing an XML file which is 1.2 GB
using SAX Parser
in Java. The result was not complete in the Console
. What I am trying to do is writing the parsed XML file into another file. Here is my code for parsing the XML file using SAX:
public class Parser extends DefaultHandler
{
public void startDocument()
{
System.out.println("Begin parsing the document .. ");
}
public void endDocument()
{
System.out.println("End parsing document ..");
}
public void startElement(String namespaceURI, String localName,String rawName, Attributes atts) throws SAXException
{
System.out.print("<" + rawName + ">");
}
public void endElement(String namespaceURI, String localName, String rawName) throws SAXException
{
System.out.print("</" + rawName + ">");
}
public void characters(char[] ch, int start, int length) throws SAXException
{
for (int i=0; i<(start + length); i++)
{
System.out.print(ch[i]);
}
}
}
Here is the main
method:
public static void main(String[] args ) throws IOException, SAXException
{
XMLReader p = XMLReaderFactory.createXMLReader();
p.setContentHandler(new Parser());
p.parse("dblp.xml");
}
I would like to write all the contents of this XML file into a text file at least. I am also thinking to write the contents into another XML file. Could anyone please help me write the XML file contents. I have tried with the following code somehow:
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
Replace your calls to System.out.print
with calls to fstream.write
- some of the calls are slightly different so read the Javadoc.
However, I am wondering why you are parsing the file if you are just trying to copy it? If your only objective is top copy it, just open an input stream, read a buffer of data and write it to your output stream, looping until you hit eof.