5

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

我对 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>();

检查现有 .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());
         }
     }

然后最终保存 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());
         }
     }

执行顺序:

        getNPCS();
    getNames(monsterList);
    getLevels(monsterList);
    getIDs(monsterList);
    combineInfo();
    checkForLine();
    saveToFile();

然而,问题在于它没有正确检查 .txt 文件中的信息。我可以看到,因为它只是保存一遍又一遍地观察到的任何东西,而不是整理任何东西。这是我有限的知识所能想到的唯一方法,但它没有奏效。

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

如果可以进一步清除问题,我可以粘贴整个脚本。

我非常感谢任何帮助,当然会记得选择我使用的答案(如果有人打扰帮助;))。

谢谢。

4

2 回答 2

6
for(String monster : monstersToAdd){    
    if(line.contains(monster)){
        monstersToAdd.remove(monster);
    }
}

将抛出一个ConcurrentModificationExceptionif line.contains(monster)istruemonstersToAddcontains monster在迭代时从集合中删除元素的唯一安全方法是使用Iterator

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

编辑

@trutheality指出

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

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

于 2011-06-15T19:31:28.443 回答
0

一个可能的问题是,当您“保存”时,您似乎正在覆盖同一个文件。我建议进行测试运行,您可以从一个文件读取并写入另一个文件。

为了附加到文件,您有几个选项:

  1. 让您的两个函数共享“RandomAccessFile”,这样在第一个函数完成读取文件后,光标位于文件末尾,第二个函数可以从那里继续写入,附加到文件
  2. 在第二个函数中打开 aRandomAccessFile并将光标移动到文件的末尾(例如通过读取其中的所有内容直到没有更多行),然后再写入。
于 2011-06-15T19:39:46.193 回答