2017-04-20 79 views
0

我想分裂一個XML文件使用以下方法,它創建第一個拆分文件沒有問題,但是當我使用output.clear();要清除已經寫入的XMLEvent數組,它會拋出錯誤。根據大小拆分XML使用Java

錯誤:異常線程「main」 javax.xml.stream.XMLStreamException:沒有元素被發現寫:java.lang.ArrayIndexOutOfBoundsException:-1

我試圖研究這個問題沒有成功,任何意見是什麼導致錯誤或如何克服它非常感謝!

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(); 
     } 
    } 
} 

回答

0

假設output是在你的類中定義的List,我覺得你的問題是,你使用output.clear()兩次。

您第一次使用output.clear()是可以的,因爲您之前添加了一個元素。

output.add(event); 

但第二次,output是空的。

解決方案

  • 您需要檢查是否使用outputoutput.clear()output.isEmpty()

  • 你也許忘了清除它之前元素添加到你的列表之前是空的。

+0

嗨Mickaël,謝謝你的回覆..我調試了程序,看看第二個循環的輸出是否爲空,但是它被成功清除並且XMLEvents再次被添加。 –

+0

造成異常的行是什麼? (XMLEvent i:output) –

+0

{xmlEventWriter.add(i); }問題似乎在這裏..我已經添加了xmlWriter.flush();在我調試時看到每個輸出,並且程序開始將元素輸出到第二個文件,但輸出2個元素並且程序終止後拋出錯誤 –