Android Studio - 保存用户数据

时间:2015-10-21 03:01:00

标签: android android-studio

我想保存一个文件" xp.txt"跟踪用户在游戏中的体验。如果文件不存在,我想创建它并写下" 0"在文件中(表示0经验)。如果文件存在,我想从中读取并将exp保存到java类中的int变量。而且我也想知道如何改变" 0"其他一些价值。

提前致谢!

我目前的代码是:

        try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput(XP, 0));
        out.write("0");
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        InputStream in = openFileInput(XP);
        if (in != null) {
            InputStreamReader temp = new InputStreamReader(in);
            BufferedReader reader = new BufferedReader(temp);
            String str;
            StringBuilder buf = new StringBuilder();
            while ((str = reader.readLine()) != null) {
                xp = Integer.parseInt(str);
                System.out.println(xp);
            }
            in.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

但是我找不到文本文件,它并没有像我预期的那样工作。

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式存储数据

  1. 共享首选项 - 将私有原始数据存储在键值中 对
  2. 内部存储 - 将私人数据存储在设备内存中。
  3. 外部存储 - 将公共数据存储在共享外部存储上。
  4. SQLite数据库 - 将结构化数据存储在私有数据库中。
  5. 网络连接 - 使用您自己的网络在网络上存储数据 服务器
  6. 我认为您的用例SharedPreferences会有用。一个简单的例子是

    保存值

    SharedPreferences.Editor editor = getSharedPreferences("unique_name", MODE_PRIVATE).edit();
    editor.putInt("xp", 10);
    editor.commit();
    

    要检索值

    SharedPreferences prefs = getSharedPreferences("unique_name", MODE_PRIVATE); 
    int xp = prefs.getInt("xp", 0); // will return 0 if no  value is saved
    

    您可以从此here了解更多信息。