![](/img/trans.png)
[英]Second calling of an method with iterator throws ConcurrentModificationException
[英]XSSFSheet removeRow(row) method throws ConcurrentModificationException
我正在嘗試讀取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++;
}
}
}
當我執行沒有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)
謝謝。
如果嘗試在迭代時使用迭代器刪除行,則會“混淆”該迭代器。 像這樣做:
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
...
另見http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.