sircrisp
sircrisp

Reputation: 1067

Why is my code not writing to file?

I am trying to read an integer from a text file when my activity starts. In my log, I only see

DEBUG: Attempt to read High Score File

and never

DEBUG: Reading High Score File

or

DEBUG: Could not read high score file

Why is my file being created by writeHighScore file but no value is being written to it.

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();
        }
    }

Upvotes: 0

Views: 47

Answers (1)

Shadow
Shadow

Reputation: 4006

I believe the issue is that you forgot to close the print writer, therefore the file can't be opened by the reader.

Simply adding a closing statement to your writeHighScore method should resolve the issue.

Upvotes: 2

Related Questions