Java - 将ArrayList中的字符串与.txt文件中的所有文本进行比较

Mik*_*aye 5 java text file arraylist bufferedwriter

实际问题将进一步解决:),谢谢.

我是Java的新手(几乎通过400页的书).

我还不熟悉API.

这是我读取.txt文件并检查是否存在已存储在.txt文件中的任何收集数据的最佳镜头.如果是这种情况,将从数据集合中删除数据,并添加.txt中尚未找到的数据.

一些变量:

public String[] names;
public int[] levels;
public int[] IDs;

public ArrayList<String> line = new ArrayList<String>();
public ArrayList<RSNPC> monsterList = new ArrayList<RSNPC>();
public ArrayList<String> monstersToAdd = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

检查现有.txt文件的方法:

    private void checkForLine() {
     try{
         // Create file 
        File file = new File(getCacheDirectory() + "output.txt");
        RandomAccessFile out = new RandomAccessFile(file, "rw");
        for(int i = 0; i < file.length(); i++){
            line.add(out.readLine());
        }
        for(String monster : monstersToAdd){    
            if(line.contains(monster)){
                monstersToAdd.remove(monster);
            }
        }
        //Close the output stream
        out.close();
     }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         }
     }
Run Code Online (Sandbox Code Playgroud)

然后最终保存checkForLine()定义的信息(已经不存在于文件中的信息)的方法:

private void saveToFile() {
     try{
         // Create file 
        BufferedWriter out = new BufferedWriter(new FileWriter(getCacheDirectory() + "output.txt"));
        for(String a : monstersToAdd){
            out.write(a);
            out.newLine();
            log("Wrote " + a + "to file");
        }
         //Close the output stream
         out.close();
         }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         }
     }
Run Code Online (Sandbox Code Playgroud)

执行顺序:

        getNPCS();
    getNames(monsterList);
    getLevels(monsterList);
    getIDs(monsterList);
    combineInfo();
    checkForLine();
    saveToFile();
Run Code Online (Sandbox Code Playgroud)

问题是,它没有正确检查.txt文件以获取信息.我可以看到,因为它只是一遍又一遍地保存它所观察到的任何东西,而不是将任何东西排序.这是我用我有限的知识思考的唯一方法,但它没有用.

对于那些想知道的人:这是一个名为RSbot的机器人脚本,它可以播放名为RuneScape的游戏.我实际上并没有使用机器人,但我想为练习做这个.

我可以粘贴整个脚本,如果这样可以进一步清理.

我真的很感激任何帮助,当然记得选择我使用过的答案(如果有人帮忙的话);).

谢谢.

Mat*_*all 6

for(String monster : monstersToAdd){    
    if(line.contains(monster)){
        monstersToAdd.remove(monster);
    }
}
Run Code Online (Sandbox Code Playgroud)

将抛出一个ConcurrentModificationExceptionif line.contains(monster)is true,并monstersToAdd包含monster.迭代时从集合中删除元素唯一安全方法是使用Iterator:

for(Iterator<String> iter = monstersToAdd.iterator(); iter.hasNext();){
    String monster = iter.next();
    if (line.contains(monster)) iter.remove();
}
Run Code Online (Sandbox Code Playgroud)

编辑

@trutheality指出

实际上,完成同样事情的一种更简单的方法是 monstersToAdd.removeAll(line);

所以你可以用for一行代码替换循环.

  • 实际上,一个更简单的方法来完成同样的事情是`monstersToAdd.removeAll(line);` (2认同)