我從字面上看通過stackoverflow試圖找到正確的答案......也許我做錯了什麼。 我正在製作我的第一個更復雜的應用程序,那就是兒童quizz應用程序。我希望將分數保存在highscorestable.txt中,稍後將打開,更新,閱讀等文件。在關閉應用程序以在下一個遊戲中重複使用該文件時,該文件應該存在,等等。 我正在使用http://developer.android.com/guide/topics/data/data-storage.html。我希望將文件保存在手機存儲器中。 我有以下代碼:如何在android中保存(永久)文件並稍後恢復數據?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_scores);
Intent intent = getIntent();
String userData;
scores =(EditText)findViewById(R.id.scores);
if(intent.getStringExtra(EndScreen.EXTRA_MESSAGE)!=null)
{
userData = intent.getStringExtra(EndScreen.EXTRA_MESSAGE);
}
else
{
userData="";
}
String temp = "";//to widzi przy zaladowaniu
String output = "";
String g="";
//FIRST READING not necessary?
try{
FileInputStream fin = openFileInput("highscorestable.txt");
int c;
while((c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
fin.close();
}
catch (Exception e) {
// e.printStackTrace();
}
if(temp.equals(null))
{
temp = "";
}
//output = userData; //+ temp;
FileOutputStream fos;//WRITING
try {
fos = openFileOutput("highscorestable.txt", Context.MODE_PRIVATE);
fos.write(userData.getBytes());
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
//READING2
try{
FileInputStream fin = openFileInput("highscorestable.txt");
int c;
while((c = fin.read()) != -1){
g = g + Character.toString((char)c);
}
fin.close();
output= output+g;
scores.setText(output);
}
catch (Exception e) {
}
工作本身的目的,其實一切正常,但是fileitself不會持續。我的意思是,當我開始一個新遊戲時,舊數據不會被恢復。如何解決它?
可以通過運行驗證假設的文件您的應用程序在模擬器上,然後使用DDMS的文件瀏覽器探索存儲?該文件是否在第二次啓動應用程序時被創建並存在?如果是這樣,那麼在恢復數據的邏輯中可能會出現錯誤。 – Egor 2015-01-04 11:29:55
OutputStream out = null; 嘗試out = new BufferedOutputStream(new FileOutputStream(「highscorestable.txt」)); }趕上(例外五){} 你嘗試過的BufferedOutputStream,因爲它可以讓你追加現有的文件。我thinkn FileOutputStream中只寫數據未追加它,所以你以前的數據是不存在的。 – 2015-01-04 11:34:56
謝謝你的回答。我會嘗試outputstream,就像它在這裏完成:http://stackoverflow.com/questions/5818406/append-data-in-existing-file-in-android-and-read-it。 - >檢查,它不工作。 Jawad Zeb,你到底意味着什麼? @Egor - DDMS - 我必須查找它。 – user3795517 2015-01-04 11:48:08