Java 为什么我的文本文件总是空的?

Java 为什么我的文本文件总是空的?,java,file,io,Java,File,Io,我创建了一个游戏,将你的高分保存在一个名为highscores.txt的文本文件中。当我打开游戏时,会显示正确的高分。但是当我打开文本文件时,它总是空的。为什么会这样?这是我写和读文本文件的代码 FileInputStream fin = new FileInputStream("highscores.txt"); DataInputStream din = new DataInputStream(fin); highScore = din.readInt(); highSScore.setT

我创建了一个游戏,将你的高分保存在一个名为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();

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

(当然,还有很多其他方法可以做到这一点)

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

(当然,还有很多其他方法可以做到这一点)

因为您正在文本编辑器中打开一个包含非文本的文件?@immibis这可能是一个很好的答案。很好。OP,如果您在Unix系统上,请尝试“xxd highscores.txt”,看看您得到的是文本还是二进制。什么是
highSScore
。您没有在代码中定义它。请提供一个完整的最小示例…尝试
FileInputStream fin=newfileinputstream(新文件(“highscores.txt”)
FileOutputStream fos=newfileoutputstream(新文件(“highscores.txt”)?我不确定这是否有帮助。因为您正在文本编辑器中打开一个包含非文本的文件?@immibis这可能是一个很好的答案。很好。OP,如果您在Unix系统上,请尝试“xxd highscores.txt”,看看您得到的是文本还是二进制。什么是
highSScore
。您没有在代码中定义它。请提供一个完整的最小示例…尝试
FileInputStream fin=newfileinputstream(新文件(“highscores.txt”)
FileOutputStream fos=newfileoutputstream(新文件(“highscores.txt”)?我不确定这是否有帮助。谢谢你的帮助,我会试试这个方法!谢谢你的帮助,我会试试这个方法!