java.util.ConcurrentModificationException问题

时间:2011-05-09 11:54:08

标签: java exception

在这段代码中,我得到一个java.util.ConcurrentModificationException,该方法在webservice中,首先读取文件并检查vakNaam是否在文件中。然后它将被删除,文件将被重写。异常2(在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;
}

2 个答案:

答案 0 :(得分:25)

错误在于此部分:

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;   
    }
} 

答案 1 :(得分:7)

Java 5增强for循环使用下面的Iterator。因此,当您从tempFile中删除时,失败快速自然会启动并抛出并发异常。使用迭代器并调用其remove方法,该方法将从基础Collection中删除。