2

I am trying to make a game with a working highscore mechanism and I am using java.io.BufferedWriter to write to a highscore file. I don't have an encryption on the highscore and I am using Slick2D and LWJGL for rendering and user input. The program executes this code:

FileWriter fstream = new FileWriter("res/gabjaphou.txt");

BufferedWriter writer = new BufferedWriter(fstream);

writer.write(score); // score is an int value

writer.close(); // gotta save m'resources! lol

I open the text file generated by this and all it reads is a question mark. I don't know why this happens, and I used other code from another project I was making and I had no problem with that... Does anyone know why? This is really annoying! :C

SuperCheezGi
  • 857
  • 3
  • 11
  • 19

3 Answers3

5

BufferedWriter.write(int) is meant to write a single charecter, not a integer.

public void write(int c)
throws IOException

Writes a single character.

Overrides: write in class Writer
Parameters: c - int specifying a character to be written
Throws: IOException - If an I/O error occurs

Try

writer.write(String.valueOf(score));  
Community
  • 1
  • 1
Nivas
  • 18,126
  • 4
  • 62
  • 76
4

Please use writer.write(String.valueOf(score)); otherwise it writes score as a character. See the documentation:

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

What you want to use is Writer.write(String); convert score to a String using String.valueOf or Integer.toString.

writer.write(String.valueOf(score));
obataku
  • 29,212
  • 3
  • 44
  • 57
  • (See comments from Nivas below) – Michael Aug 09 '12 at 02:12
  • @TehHippo I originally commented on the question and then posted the answer here before Nivas. – obataku Aug 09 '12 at 02:13
  • @SuperCheezGi since you appear newer here, please don't forget to mark the answer [accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) which helped most in solving the problem. – obataku Aug 15 '12 at 05:29
0

BufferedWriter is attempting to write a series of bytes to the file, not numbers. A number is still a character.

Consider using FileWriter instead, and something as simple as: fileWriter.write(Integer.toString(score)) Write takes a string here, but the output should be the same.

Michael
  • 1,014
  • 1
  • 8
  • 23