2015-05-31 31 views
0

我創建了一個遊戲,將您的高分保存在名爲highscores.txt的文本文件中。當我打開遊戲時,顯示正確的高分。但是當我打開文本文件時,它總是空的。爲什麼是這樣?這是我編寫和閱讀文本文件的代碼。爲什麼我的文本文件總是空的?

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(); 
+5

因爲你在文本編輯器中打開一個包含非文本的文件? – immibis

+0

@immibis這可能是一個很好的答案。 – Sinkingpoint

+0

好的。 OP,如果你使用的是Unix系統,請嘗試「xxd highscores.txt」,看你是否得到文本或二進制文件。 –

回答

4

DataOutputStream.writeInt不寫入整數作爲文本;它寫入由4個字節組成的「原始」或「二進制」整數。如果你試圖將它們解釋爲文本(例如通過在文本編輯器中查看它們),你會得到垃圾,因爲它們不是文本。

例如,如果您的分數爲100,writeInt將寫入0字節,0字節,0字節和100字節(按此順序)。 0是無效字符(當解釋爲文本時),而100恰好是字母「d」。

如果你想要寫一個文本文件,你可以使用Scanner解析(讀取)和PrintWriter寫作 - 這樣的事情:

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

(當然,還有很多其他的方法可以做到這個)

+0

謝謝你的幫助我會試試這個方法! –

相關問題