java - Why is my text file always empty? -
i have created game saves high score in text file called highscores.txt. when open game, correct high score displayed. when open text file, empty. why this? here code writing , reading 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();
dataoutputstream.writeint
not write integer text; writes "raw" or "binary" integer consisting of 4 bytes. if try interpret them text (such viewing them in text editor), garbage, because they're not text.
for example, if score 100, writeint
write 0 byte, 0 byte, 0 byte, , 100 byte (in order). 0 invalid character (when interpreted text) , 100 happens letter "d".
if want write text file, use scanner
parsing (reading) , printwriter
writing - this:
// reading filereader fin = new filereader("highscores.txt"); scanner sc = new scanner(fin); highscore = din.nextint(); highscore.settext("high score: " + highscore); sc.close(); // writing filewriter fos = new filewriter("highscores.txt"); printwriter pw = new printwriter(fos); pw.println(highscore); pw.close();
(of course, there many other ways this)
Comments
Post a Comment