0
我目前遇到在內部存儲器上保存文本文件的問題。如何在內部存儲器上持久保存文件
問題是,只要我退出應用程序,該文件似乎被刪除。
我寫這個方法被調用的應用程序的啓動,創建一個空白的文本文件:
private void init() {
String FILE_NAME = "save.txt";
try {
new BufferedWriter(new FileWriter(getFilesDir() + FILE_NAME));
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
調用該函數讀取寫入其中的所有行:
private List<String> readFromFile() {
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
return ret;
}
而且finaly調用此方法追加在文本文件中的字符串,如果它不是已經在它:
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if(!ret.contains(unNom)){
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = new FileOutputStream(getFilesDir() +FILE_NAME);
for (String ligne: ret) {
ligne+="\n";
fos.write(ligne.toString().getBytes());
}
fos.flush();
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
如何正確保存內部存儲器中的文件?
對不起,我的英文不好, 謝謝你的幫忙!