实际的问题会在下面进一步解决 :),谢谢。
我是 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 的游戏。我实际上并没有使用该机器人,但我想在练习中使用它。
我可以粘贴整个脚本,如果这样可以进一步解决问题的话。
我非常感谢任何帮助,当然会记得选择我使用的答案(如果有人愿意帮忙 ;))。
谢谢。
最佳答案
for(String monster : monstersToAdd){
if(line.contains(monster)){
monstersToAdd.remove(monster);
}
}
如果 line.contains(monster)
为 true
,并且 monstersToAdd
包含 ,将抛出
。 The only safe way to remove an element from a collection while iterating is to use ConcurrentModificationException
>怪物Iterator
:
for(Iterator<String> iter = monstersToAdd.iterator(); iter.hasNext();){
String monster = iter.next();
if (line.contains(monster)) iter.remove();
}
编辑
Actually, a much simpler way to accomplish the same thing is
monstersToAdd.removeAll(line);
因此您可以用一行代码替换 for
循环。
关于Java - 将 ArrayList 中的字符串与 .txt 文件中的所有文本进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6363127/