I am trying to read xlsx file. I am using 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. But when I add removeRow call it throws XmlValueDisconnectedException exception.
Can any one please help me why I am getting this exception.
Update:
I am quite surprised but now I am getting ConcurrentModificationException
exception. Once it executes removeRow() and then when it returns to rowIterator.next() it throws the exception. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.