gooly bug
gooly bug

Reputation: 135

Why is my text file always empty?

I have created a game that saves your high score in a text file called highscores.txt. When I open the game, the correct high score is displayed. But when I open the text file, it is always empty. Why is this? Here is my code for writing and reading the text file.

FileInputStream fin = new FileInputStream("highscores.txt");
DataInputStream din = new DataInputStream(fin);

highScore = din.readInt();
highSScore.setText("High Score: " + highScore);
din.close();

FileOutputStream fos = new FileOutputStream("highscores.txt");
DataOutputStream dos = new DataOutputStream(fos);

dos.writeInt(highScore);
dos.close();

Upvotes: 0

Views: 771

Answers (1)

DataOutputStream.writeInt does not write an integer as text; it writes a "raw" or "binary" integer consisting of 4 bytes. If you try to interpret them as text (such as by viewing them in a text editor), you get garbage, because they're not text.

For example, if your score is 100, writeInt will write a 0 byte, a 0 byte, a 0 byte, and a 100 byte (in that order). 0 is an invalid character (when interpreted as text) and 100 happens to be the letter "d".

If you want to write a text file, you could use Scanner for parsing (reading) and PrintWriter for writing - something like this:

// for reading
FileReader fin = new FileReader("highscores.txt");
Scanner sc = new Scanner(fin);

highScore = din.nextInt();
highScore.setText("High Score: " + highScore);
sc.close();

// for writing
FileWriter fos = new FileWriter("highscores.txt");
PrintWriter pw = new PrintWriter(fos);
pw.println(highScore);
pw.close();

(of course, there are many other ways you could do this)

Upvotes: 4

Related Questions