[英]XSSFSheet removeRow(row) method throws ConcurrentModificationException
I am trying to read xlsx file. 我正在尝试读取xlsx文件。 I am using poi 3.10-FINAL.
我正在使用poi 3.10-FINAL。
My code is 我的代码是
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++;
}
}
}
When I execute my code without sheet.removeRow(row)
, it works fine. 当我执行没有
sheet.removeRow(row)
代码时,它工作正常。 But when I add removeRow call it throws XmlValueDisconnectedException exception. 但是当我添加removeRow调用它时会抛出XmlValueDisconnectedException异常。
Can any one please help me why I am getting this exception. 任何人都可以帮助我为什么我得到这个例外。
Update: 更新:
I am quite surprised but now I am getting ConcurrentModificationException
exception. 我很惊讶,但现在我收到
ConcurrentModificationException
异常。 Once it executes removeRow() and then when it returns to rowIterator.next() it throws the exception. 一旦执行removeRow(),然后它返回rowIterator.next(),它就会抛出异常。 I have mentioned location of exception in the code.
我在代码中提到了异常的位置。 The stack trace is
堆栈跟踪是
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)
Thanks. 谢谢。
If you try to remove a row using an iterator while iterating, you "confuse" the iterator. 如果尝试在迭代时使用迭代器删除行,则会“混淆”该迭代器。 Do it like this:
像这样做:
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
...
See also http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html 另见http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.