0

我收到一些人的录音。我想给他们身份证。我正在尝试.txt在包含新 id 值的 Android sdcard0 中保存一个文件。

我的意思是,我打开新人的应用程序。程序从 txt 文件中读取最后一个 id 值。然后将 +1 值添加到新人的 id。并更新.txt文件内容。

后来我关闭了应用程序。然后,我再次打开应用程序,读取最后一个 id 值,并保存另一个人 id +1 的声音。我想.txt在每次应用程序打开时动态更新 Android sdcard0 内存中的文件 ID 内容。

我怎样才能做到这一点?请帮我。这是我的简单代码。

enter cod private String Load() {
String result = null;;
String FILE_NAME = "counter.txt";

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "Records";
    File file = new File(baseDir, FILE_NAME);

   int counter = 0;
    StringBuilder text = new StringBuilder();

    try {
        FileReader fReader = new FileReader(file);
        BufferedReader bReader = new BufferedReader(fReader);
        //.....??....

        }
        result = String.valueOf(text);
    } catch (IOException e) {
        e.printStackTrace();
    }

return result;

}

4

2 回答 2

1

如果我理解正确,您希望每次打开应用程序时都将 lastid+1 添加到您的文本文件中。你也想在你的 SD 卡上存储和编辑这个文件!

有 3 个步骤可以尝试完成此操作:

  1. 从文件中读取
  2. 查找最后添加的 id
  3. 将新 id 写入文本文件
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard, "counter.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String lastLine = "";

    while ((sCurrentLine = br.readLine()) != null) 
    {
        lastLine = sCurrentLine;
    }

    br.close();
    //Parse the string into an actual int.
    int lastId = Integer.parseInt(lastLine);


    //This will allow you to write to the file
    //the boolean true tell the FileOutputStream to append
    //instead of replacing the exisiting text
    outStream = new FileOutputStream(file, true);
    outStreamWriter = new OutputStreamWriter(outStream); 
    int newId = lastId + 1;

    //Write the newId at the bottom of the file!
    outStreamWriter.append(Integer.toString(newId));
    outStreamWriter.flush();
    outStreamWriter.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

写入 SD 卡等外部存储需要您的 Android 清单中的特殊权限,只需添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

那应该这样做!

有关参考资料,请查看以下链接:

如何在 Android 中读取文本文件?

如何使用java读取文本文件中的最后一行

android作为文本文件保存到SD卡

将文本附加到文件末尾

于 2015-02-11T10:50:23.650 回答
0

如果您想要的只是持久的原始数据,例如保存/加载一个 int 值,您应该使用 android 共享首选项机制: 共享首选项示例

于 2015-02-11T11:19:09.823 回答