[英]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個步驟來嘗試完成此操作:
- 從文件讀取
- 查找最后添加的ID
- 將新的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" />
那應該做到的!
對於參考資料,請查看以下鏈接:
如果您想要的只是持久性原始數據(例如保存/加載int值),則應使用android共享首選項機制: 共享首選項示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.