I am trying to split an XML file using the following method, it created the first split file no problem but when i use output.clear(); to clear the Array of XMLEvents that already have been written it throws an error.
error: Exception in thread "main" javax.xml.stream.XMLStreamException: No element was found to write: java.lang.ArrayIndexOutOfBoundsException: -1
i tried to investigate this issue with no success, any advice on what is causing the error or how to overcome it greatly appreciated!
public void SplitBySize() throws FileNotFoundException, XMLStreamException, IOException {
//File Path
String filePath = "C:\\Users\\thamm\\Desktop\\XMLFile\\Data2.xml";
//Read XML file.
Reader fileReader = new FileReader(filePath);
//Get XMLInputFactory instance.
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
//Create XMLEventReader object.
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(fileReader);
long charCount = 0;
int fileNumber = 1;
while (xmlEventReader.hasNext()) {
XMLEvent event = xmlEventReader.nextEvent();
charCount++;
output.add(event);
if (charCount == MAX_SIZE) {
XMLEventWriter xmlEventWriter = factory.createXMLEventWriter(new FileWriter("C:\\Users\\thamm\\Desktop\\SplitFiles\\output_part_" + fileNumber + ".xml"));
for (XMLEvent i : output) {
xmlEventWriter.add(i);
}
xmlEventWriter.close();
output.clear();
charCount = 0;
fileNumber++;
}
if (event.isEndDocument()) {
XMLEventWriter xmlEventWriter = factory.createXMLEventWriter(new FileWriter("C:\\Users\\thamm\\Desktop\\SplitFiles\\output_part_End.xml"));
for (XMLEvent i : output) {
xmlEventWriter.add(i);
}
xmlEventWriter.close();
output.clear();
}
}
}