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();
}
}
看起來你的文件是空的。 – shmosel
你的代碼寫到同一個文件的地方在哪裏? –
你能告訴我們那個文件裏面還有什麼嗎? –