当我开始活动时,我正在尝试从文本文件读取整数。在我的日志中,我只看到
调试:尝试读取高分文件
绝不
调试:阅读高分文件
或者
调试:无法读取高分文件
为什么我的文件是由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();
}
}
我相信问题是您忘记了关闭打印编写器,因此阅读器无法打开该文件。
只需在writeHighScore
方法中添加结束语句即可解决该问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句