java - 使用 arrayList 更新文件中的记录

标签 java file-io arraylist

我有一个正在玩游戏的用户列表。他们有一些统计数据,我将其存储在 arrayList newList 中。游戏退出后,我将 arrayList 值存储在 .dat 文件中。现在的问题是,如果用户已存在于我的 .dat 文件中,我将需要更新该用户的记录。我想在这里使用 3 个 arrayList。

1. ArrayList newList will get the records from the file.
2. ArrayList oldList will then store the replica of newList.
3. Game ends. Compare arrayList newList and oldList, and store the updated list in ArrayList users.
4. Store the ArrayList users in a file.

void compare()
    {
        Player obj1=null,obj2=null;
        int newSize = newList.size();   //stores the new records of the users.
        int oldSize = oldList.size();   //stores the old records of the users.
        for(int i=0;i<oldSize;i++)
        {
            for(int j=0;j<newSize;j++)
            {
                obj1=newList.get(i);
                obj2=oldList.get(j);
                if(obj1==obj2)
                {
                    users.add(obj1);
                }
                else
                {
                    users.add(obj2);
                }
            }

        }
    }

//store the records of users in the filename.dat

这个逻辑行得通吗?

最佳答案

使用纯文件存储“ session 数据”可能不是最好的方法,您可能会发现与并发、I/O 阻塞等相关的问题。

在你的情况下,我会使用一些嵌入式数据库,例如 SQLiteH2 ,我在类似的场景中使用过 H2,效果非常好。

但是,如果您想(出于任何原因)自己将数据存储在文件中,那么我建议使用 Map 而不是 List,使用用户名作为键或任何其他唯一字段来识别用户,这样您就可以轻松地获取用户是否存在。

另一方面,你的代码没有太大意义,也许我不明白你的意思,我会使用类似于这样的代码:

  List<Player> users = new ArrayList<Player>(oldList);

  for(String newUser: newList)
  {
      if (!users.contains(newUser)) {
          users.add(newUser);
      }
  }

以前的代码,获取所有oldUsers并添加旧列表中未包含的新用户,¿这是您需要的吗?

关于java - 使用 arrayList 更新文件中的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720363/

相关文章:

java - 使用 JPA 存储库的通配符字段 QueryByExample

java - 有什么(任何方式)可以比 StringWriter 更快地连接 java 字符串吗?

java - 在 intellij 上调试评估表达式

c++ - 如何使用 QByteArray 读取 16 位整数

java - 将 3 个列表组合成具有唯一值的单个集合

c# - 无法将带 [] 的索引应用于类型 `object' 的表达式

java - JProgressbar:如何根据进度改变颜色?

java - 如何通过知道行的位置来从文件中删除行?

java - 文本文件io和换行符

java - 根据JAVA成绩比较学生