2016-01-10 67 views
0

我有下一個問題:讀取和寫入文件android

(1)如何檢查文件是否存在?我做這樣的MainActivityonCreate

File f = new File("punteggio.txt"); 
if(f.exist()) 
    readFromFile(); 
else{ 
    writeToFile(); 
    readFromFile(); 
} 

,但因爲每次我打開我的應用程序文件時,它不存在,不能正常工作。

(2)另一個問題。 在我的第一個活動中,我從文件中書寫和讀取沒有問題,而在第二個活動中,當我從文件讀取字符串爲空時。

主要活動

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    textScore = (TextView) findViewById(R.id.textRecord); 
    File f = new File("punteggio.txt"); 
    if (!f.exists()) { 
     Log.d(TAG, "Writeee"); 
     writeToFile(); 
    } else { 
     readFromFile(); 
    } 
} 

private void readFromFile() { 
    String ret = ""; 
    try { 
     FileInputStream fis = openFileInput("punteggio.txt"); 
     byte[] buffer = new byte[(int) fis.getChannel().size()]; 
     fis.read(buffer); 
     String str = ""; 
     for (byte b : buffer) str += (char) b; 
     fis.close(); 
     Log.d(TAG, str); 
     textScore.setText("Record: " + str); 
     Log.i("STACKOVERFLOW", String.format("GOT: [%s]", str)); 
    } catch (IOException e) { 
     Log.e("STACKOVERFLOW", e.getMessage(), e); 
    } 
} 

public void startGame(View v) { 
    Intent i = new Intent(MainActivity.this, GamePanel.class); 
    startActivity(i); 
} 

private void writeToFile() { 
    String string = "0"; 
    try { 
     FileOutputStream fos = openFileOutput("punteggio.txt", Context.MODE_PRIVATE); 
     fos.write(string.getBytes()); 
     fos.flush(); 
     fos.close(); 
    } catch (IOException e) { 
     Log.e(TAG, e.getMessage(), e); 
    } 
} 

這是secondActivity

private int readFromFile() { 
    String str = ""; 
    int i = 0; 

    try { 
     FileInputStream fis = openFileInput("punteggio.txt"); 
     byte[] buffer = new byte[(int) fis.getChannel().size()]; 
     fis.read(buffer); 
     for (byte b : buffer) str += (char) b; 
     i = Integer.parseInt(str); 
     fis.close(); 
    } catch (IOException e) { 
     Log.e("STACKOVERFLOW", e.getMessage(), e); 
    } 
    Log.d(TAG, "Stringa iiiii: " + i); 
    return i; 
} 

變量是空的,爲什麼呢? 你能幫我嗎?謝謝

回答

1

答案爲(1) - 打開和寫入文件取決於文件的位置,它可能在手機存儲或SD卡中。因此,在實施閱讀文件系統時,應考慮文件的位置。這有時會導致錯誤,無法找到文件。 或者,更好的做法是使用份額偏好。

旁註:因爲用戶可以直接編輯文本文件中的分數並改變遊戲結果,所以將遊戲分數存儲在文本文件中是脆弱的。

+0

所以我使用數據庫。是正確的? –

+0

股票優惠是一種存儲價值成對的方式...更多的信息在這裏 - > http://developer.android.com/reference/android/content/SharedPreferences.html –

+0

感謝您的幫助 –