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

发布于 2024-11-15 15:10:13 字数 2353 浏览 2 评论 0原文

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

我对 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 的机器人的脚本,它可以玩名为 RSbot 的游戏符文景观。我实际上并没有使用该机器人,但我想这样做是为了练习。

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

我真的很感谢任何帮助,当然会记得选择我使用的答案(如果有人愿意帮忙的话;))。

谢谢。

The actual problem will be addressed a bit further down :), thanks.

I'm fairly new to Java (nearly through a 400 page book).

I'm not really that familiar with the API yet.

This is my best shot at reading a .txt file and checking if there are any of the collected data that already is stored in the .txt file. If that is the case, the data will be removed from the data collection, and the data that isn't already found in the .txt will be added.

Some variables:

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

The method that checks the existing .txt file:

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

The method that then finally saves the information that the checkForLine() defined (the one already not in the file):

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

The order of execution:

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

The problem however, is that it doesn't correctly check for the .txt file for information. I can see that because it just saves whatever it observes over and over again, not sorting anything away. This was the only way I could think of with my limited knowledge, and it didn't work.

For those wondering: This is a script for a bot called RSbot that plays the game called RuneScape. I don't actually use the bot, but I wanted to do this for the exercise.

I can paste the entire script if that would clear up things further.

I really appreciate any help, and will of course remember to select the answer that I used (if anyone bothers helping out ;) ).

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光沙漏 2024-11-22 15:10:13
for(String monster : monstersToAdd){    
    if(line.contains(monster)){
        monstersToAdd.remove(monster);
    }
}

如果 line.contains(monster)true,并且 monstersToAdd 包含 monster<,则会抛出 ConcurrentModificationException /代码>。 唯一安全的删除方法迭代时集合中的元素是使用 Iterator

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

编辑

@trutheality 点 出去

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

因此,您可以用一行代码替换 for 循环。

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

will throw a ConcurrentModificationException if line.contains(monster) is true, and monstersToAdd contains monster. The only safe way to remove an element from a collection while iterating is to use Iterator:

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

Edit

@trutheality points out

Actually, a much simpler way to accomplish the same thing is monstersToAdd.removeAll(line);

So you can replace the for loop with one line of code.

海未深 2024-11-22 15:10:13

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

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

  1. 让两个函数共享“RandomAccessFile”,这样第一个函数读取文件后,光标位于文件末尾,第二个函数位于文件末尾可以从那里继续写入,附加到文件
  2. 在第二个函数中打开一个 RandomAccessFile 并将光标移动到文件末尾(例如,读取其中的所有内容,直到没有更多行)在写作之前。

One possible problem is that you seem to be overwriting the same file when you "save". I suggest making a test run where you read from one file and write to the other.

In order to append to the file, you have a couple of options:

  1. Have your two functions share the 'RandomAccessFile`, that way after the first one is done reading the file, the cursor is at the end of the file and the second function can proceed to write from there, appending to the file
  2. Open a RandomAccessFile in the second function and move the cursor to the end of the file (for example by reading everything in it until there are no more lines) before writing.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文