使用arrayList更新文件中的记录

时间:2014-05-18 09:14:20

标签: 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

这种逻辑会起作用吗?

1 个答案:

答案 0 :(得分:1)

使用普通文件存储“会话数据”可能不是最好的方法,您可以找到与并发,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并添加旧列表中未包含的新用户,¿这是您需要的吗?