XSSFSheet removeRow(row)方法抛出ConcurrentModificationException

Nam*_*ala 2 java xlsx apache-poi

我正在尝试阅读xlsx文件.我正在使用poi 3.10-FINAL.

我的代码是

FileInputStream fs = new FileInputStream("abc.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fs);
row_count = 0;

for (int k = 0; k < wb.getNumberOfSheets(); k++) {
    XSSFSheet sheet = wb.getSheetAt(k);
    if (sheet.getLastRowNum() > 0) {
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next(); // throws ConcurrentModificationException
            if (row_count == 0) {
                col_count = row.getLastCellNum();
                //Do something
            } else {
                if (row.getCell(1).equals("XYZ")) {
                    sheet.removeRow(row);  //throws XmlValueDisconnectedException
                }
            }
            row_count++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我执行我的代码时sheet.removeRow(row),它工作正常.但是当我添加removeRow调用它时会抛出XmlValueDisconnectedException异常.

任何人都可以帮助我为什么我得到这个例外.

更新:

我很惊讶,但现在我变得ConcurrentModificationException异常了.一旦执行removeRow(),然后它返回rowIterator.next(),它就会抛出异常.我在代码中提到了异常的位置.堆栈跟踪是

java.util.ConcurrentModificationException
    at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
    at java.util.TreeMap$ValueIterator.next(Unknown Source)
    at com.test.app.services.ExecuteImport.uploadFile(ExecuteImport.java:144)
    at com.test.app.controller.MyController.upload(MyController.java:271)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

谢谢.

Mir*_*rco 7

如果在迭代时尝试使用迭代器删除行,则会"混淆"迭代器.像这样做:

List<Row> toRemove = new ArrayList<Row>()
  while (rowIterator.hasNext()) {
            Row row = rowIterator.next(); // throws ConcurrentModificationException
            if (row_count == 0) {
                col_count = row.getLastCellNum();
                //Do something
            } else {
                if (row.getCell(1).equals("XYZ")) {
                  toRemove.add(row);
                }
            }
            row_count++;
        }
// loop the list and call sheet.removeRow() on every entry
    ...
Run Code Online (Sandbox Code Playgroud)

另见http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html