我收到了一些人的语音记录。我想给他们id。我正在尝试在 Android sdcard0 中保存一个 .txt
文件,其中包含新的 id 值。
我的意思是,我为新人打开申请。程序从 txt 文件中读取最后一个 id 值。然后给新人的id加+1。并更新.txt
文件内容。
后来我关闭了应用程序。然后,我再次打开应用程序,读取最后一个 id 值,并使用 person 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 个步骤来尝试实现此目的:
- Read from the file
- Find the last added id
- Write the new id to the text file
//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 list 中添加特殊权限,只需添加
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这样就可以了!
有关引用资料,请查看以下链接:
How can I read a text file in Android?
how to read last line in a text file using java
关于java - 每次打开应用程序时,在 Android sdcard0 中动态保存 .text 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28451024/