java.util.ConcurrentModificationException问题

标签 java exception

在此代码中,我收到 java.util.ConcurrentModificationException 该方法位于 Web 服务中,首先读取文件并检查 vakNaam 是否在文件中。然后它将被删除并且文件将被重写。异常由 Exception2 引发(在 println 中)

        @WebMethod
        public boolean removeVak(String naam){
    ArrayList<String> tempFile = new ArrayList<String>();

    //Read the lines
    boolean found = false;
    BufferedReader br = null;
            try {
        br = new BufferedReader(new FileReader("C:/vak.txt"));
        String strLine;         
        while ((strLine = br.readLine()) != null){
            tempFile.add(strLine);
        }
    }catch(Exception e){
        System.out.println("Exception " + e);
    }finally {          
        try {
            if (br != null)
                br.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //Write the lines
    BufferedWriter out= null;
    try{
        for(String s : tempFile){
            String [] splitted = s.split(" ");
            if(splitted[0].equals(naam)){
                tempFile.remove(s);
                found = true;   
            }
        }           
        out = new BufferedWriter(new FileWriter("C:/vak.txt", false));
        for(String s: tempFile){                
            out.newLine();
            out.write(s);               
        }
        out.close();

    } catch (Exception e) {
        System.out.println("Exception2 " + e);
        return false;
    }finally {          
        try {
            if (out != null)
                out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }       
    return found;
}

最佳答案

错误在这部分:

for (String s : tempFile){
    String [] splitted = s.split(" ");
    if (splitted[0].equals(naam)){
        tempFile.remove(s);
        found = true;   
    }
} 

不要修改您正在迭代的列表。您可以通过显式使用 Iterator 来解决此问题:

for (Iterator<String> it = tempFile.iterator(); it.hasNext();) {
    String s = it.next();
    String [] splitted = s.split(" ");
    if (splitted[0].equals(naam)){
        it.remove();
        found = true;   
    }
} 

关于java.util.ConcurrentModificationException问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936501/

相关文章:

Java JSTL foreach

c# - 抛出异常但保留堆栈跟踪

java - 捕获 IllegalArgumentException 的最佳方法是什么

asp.net-mvc - ASP.net MVC [HandleError] 未捕获异常

android从客户经理那里获取gmail用户名和密码

C++ 异常抛出语法

java - 无法使用 java 中的反射调用带有变量参数的方法

Java 多重边界

java - 我如何在java中使用setPreferredSize?

java - 如何用Ebean Java ORM语言编写join