2016-03-13 29 views
0

我想在我的活動開始時從文本文件中讀取一個整數。 在我的日誌,我只看到爲什麼我的代碼不寫入文件?

DEBUG:嘗試讀取高分文件

永不

DEBUG:閱讀高分文件

DEBUG:無法讀取高分檔案

爲什麼我的文件是通過writeHighScore文件創建的,但是沒有值被寫入它。

public class GameScreen extends AppCompatActivity implements View.OnClickListener { 

private Simon simon = new Simon();; 
private int score = 0; 
private int highScore = 0; 
private String highScoreString; 
private String FILENAME = "highscore.txt"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game_screen); 

    //Read highScore file 
    TextView highScoreTV = (TextView) findViewById(R.id.high_score_tv); 

    Log.i("DEBUG", "Attempt to read High Score File"); 

    try{ 
     FileInputStream fis = openFileInput(FILENAME); 
     Scanner scanner = new Scanner(fis); 
     if(scanner.hasNext()){ 
      Log.i("DEBUG", "Reading High Score File"); 
      highScoreString = scanner.nextLine(); 
      highScore = Integer.getInteger(highScoreString); 
     } 
     scanner.close(); 
    } catch (FileNotFoundException e){ 
     Log.e("READ ERROR", "Could not read high score: " + e.getMessage()); 
    } 
    highScoreTV.setText(""+highScore); 
} 

writeHighScore

private void writeHighScore(){ 
     try { 
      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
      OutputStreamWriter osw = new OutputStreamWriter(fos); 
      BufferedWriter bw = new BufferedWriter(osw); 
      PrintWriter pw = new PrintWriter(bw); 
      Log.i("DEBUG", "Writing High Score File"); 
      pw.println("" + score + "\n"); 
     } catch (FileNotFoundException e) { 
      Log.e("WRITE ERROR", "Cannot Save: " + e.getMessage()); 
      e.printStackTrace(); 
      Toast.makeText(GameScreen.this, "Error Saving", Toast.LENGTH_SHORT).show(); 
     } 
    } 
+2

看起來你的文件是空的。 – shmosel

+0

你的代碼寫到同一個文件的地方在哪裏? –

+0

你能告訴我們那個文件裏面還有什麼嗎? –

回答

2

我認爲,問題是,你忘了關閉打印作家,因此該文件不能被讀取器打開。

只需在您的writeHighScore方法中添加結語即可解決問題。

+0

這是解決方案! 這是我第二次處理文件io,我想我錯過了那部分,而從我的舊代碼複製。 – sircrisp

相關問題