2011-09-21 86 views
0

我正在學習Android,我正在製作一些基本的數學程序(遊戲)。它會得到兩個隨機數,隨機算子和30秒來儘可能地解決數學問題。如果你解決問題你得到1分。讀取和寫入文件Android

無論如何,現在我想獲得用戶已經完成的點數,並將其寫入文件,然後再讀取它(現在只是記錄它)。

當我點擊按鈕,寫入文件,它和我得到這個日誌消息: 09-21 21:11:45.424:DEBUG /寫(778):這是寫日誌:2

呀,似乎它寫道。奧基,讓我們讀一讀。

09-21 21:11:56.134:DEBUG /讀日誌(778):這是讀日誌:2

它讀取它。

但是當我再次嘗試寫入時,它似乎會覆蓋以前的數據。 (778):這是寫日誌:1 09-21 21:17:28.334:DEBUG/Reading日誌(778):這是讀日誌:1

正如你所看到的,它只是讀取最後一個輸入。

這是代碼的一部分,我正在寫和讀它。

public void zapisi() { 
    // WRITING 
    String eol = System.getProperty("line.separator"); 
    try { 
     FileOutputStream fOut = openFileOutput("samplefile.txt", 
       MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 

     osw.write(poenibrojanje+eol); 
     //for(int i=0;i<10;i++){ 
     Log.d("Writing","This is writing log: "+poenibrojanje); 
     //} 

     //osw.flush(); 
     osw.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


private void citaj() { 

    // READING 

    String eol = System.getProperty("line.separator"); 
    try { 
     BufferedReader input = new BufferedReader(new InputStreamReader(
       openFileInput("samplefile.txt"))); 
     String line; 
     StringBuffer buffer = new StringBuffer(); 
     while ((line = input.readLine()) != null) { 
      buffer.append(line + eol); 
     } 
     //TextView textView = (TextView) findViewById(R.id.result); 
     Log.d("Reading log","This is reading log:"+buffer); 
     System.out.println(buffer); 
     //tvRezultat.setText(buffer.toString()); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

回答

1

可以使用openFileOutput( 「samplefile.txt」,MODE_APPEND)

+0

你能解釋一下好一點?當我試試這個:FileOutputStream中FOUT = openFileOutput(「samplefile.txt」,真正 \t \t \t \t \t MODE_WORLD_READABLE)我得到這個錯誤:在類型ContextWrapper的方法openFileOutput(字符串,整數)不適用的參數(字符串,boolean); – Zookey

+0

噢,現在當我試圖讀取它時,ffs會出現此錯誤,或者寫入:09-21 21:46:19.185:WARN/System.err(832):java.io.FileNotFoundException:/samplefile.txt – Zookey

+0

你的文件路徑有問題。你在哪裏保存文件? – Manos