【发布时间】:2011-09-15 19:52:36
【问题描述】:
实际的问题会在后面解决 :),谢谢。
我对 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 的游戏。我实际上并没有使用机器人,但我想在练习中这样做。
如果可以进一步澄清问题,我可以粘贴整个脚本。
我非常感谢任何帮助,当然会记得选择我使用的答案(如果有人愿意帮忙;))。
谢谢。
【问题讨论】:
-
“不排序任何东西” - 我在这里看不到任何执行排序的实际代码。
-
@Matt Ball "filtering" -- 这就是为什么没有 CME ;)
-
建议在iterface写
List<String> x = new ArrayList<String>()而不是ArrayList<String> y = new ArrayList<String>()代码,而不是实现。 :) -
@pst:我希望 readLine() 实际上只是将它读取的行作为字符串返回,这将匹配怪物,但我可以从你那里得知它没有:/。 .似乎真的找不到任何其他有用的方法atm。
标签: java file text arraylist bufferedwriter