2015-05-31 32 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

谢谢你的帮助我会试试这个方法! –

相关问题