Java – 将ArrayList中的字符串与.txt文件中的所有文本进行比较
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java – 将ArrayList中的字符串与.txt文件中的所有文本进行比较,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2513字,纯文字阅读大概需要4分钟。
内容图文
实际问题将进一步解决:),谢谢.
我是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,则会抛出ConcurrentModificationException,并且monstersToAdd包含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();
}
编辑
Actually, a much simpler way to accomplish the same thing is
monstersToAdd.removeAll(line);
所以你可以用一行代码替换for循环.
内容总结
以上是互联网集市为您收集整理的Java – 将ArrayList中的字符串与.txt文件中的所有文本进行比较全部内容,希望文章能够帮你解决Java – 将ArrayList中的字符串与.txt文件中的所有文本进行比较所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。