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

Why is my text file always empty?

我创建了一个游戏,将您的高分保存在一个名为 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 个字节组成的 "raw" 或 "binary" 整数。如果您尝试将它们解释为文本(例如通过在文本编辑器中查看它们),您会得到垃圾,因为它们不是文本。

例如,如果您的分数是 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();

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