繁体   English   中英

每次打开应用程序时,在Android sdcard0中动态保存.txt文件

[英]Saving a .txt file dynamically in Android sdcard0 when everytime applicaiion opens

我从某些人那里获得语音记录。 我想给他们身份证。 我正在尝试在包含新ID值的Android sdcard0中保存.txt文件。

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

稍后我关闭该应用程序。 然后,我再次打开该应用程序,读取最后一个id值,并保存人id为+1的另一个人的声音。 我想在每次打开应用程序时动态更新Android sdcard0内存中的.txt文件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;

}

如果我理解正确,那么您想在每次打开应用程序时将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 Manifest中的特殊权限,只需添加

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

那应该做到的!

对于参考资料,请查看以下链接:

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

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

android将文本文件保存到SD卡

将文本附加到文件末尾

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM