java.util.ConcurrentModificationException问题 [英] java.util.ConcurrentModificationException problem

查看:325
本文介绍了java.util.ConcurrentModificationException问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我得到一个java.util.ConcurrentModificationException,该方法在webservice中,首先读取文件并检查vakNaam是否在文件中。然后它将被删除,文件将被重写。 Exception2抛出异常(在println中)

On this code I get an java.util.ConcurrentModificationException the method is in a webservice and first reads the file and checks if the vakNaam is in the file. Then it will be removed and the file will be rewritten. The exception is thrown by Exception2 (in the 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 解决此问题:

Don't modify the list you are iterating over. You could solve this by using the Iterator explicitely:

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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆