我正在尝试在活动开始时从文本文件中读取整数。 在我的日志中,我只看到
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();
}
}
答案 0 :(得分:2)
我认为问题是您忘记关闭打印作者,因此读者无法打开该文件。
只需在#:kivy 1.9.1
<TheBox>:
FloatLayout:
FloatLayout:
size: 810, 1080
pos_hint: {'center_x': .21}
Image:
canvas.before:
Color:
rgb: (0, 0, 0)
Rectangle:
pos: self.pos
size: self.size
id: PetL_photo
size_hint: None, None
size: 790, 770
pos_hint: {'center_x': .5, 'center_y': .64}
allow_stretch: True
keep_ratio: True
source:
Label:
..
Label:
..
Label:
..
Label:
..
FloatLayout:
..
FloatLayout:
size: 810, 1080
pos_hint: {'center_x': .79}
Image:
canvas.before:
Color:
rgb: (0, 0, 0)
Rectangle:
pos: self.pos
size: self.size
id: PetR_photo
size_hint: None, None
size: 790, 770
pos_hint: {'center_x': .5, 'center_y': .64}
allow_stretch: True
keep_ratio: True
source:
Label:
..
Label:
..
Label:
..
Label:
..
方法中添加结束语句即可解决问题。