如何在每次调用该方法时停止BufferedWriter分配空值?
我正在研究游戏,我想将高分存储在文件中,并在需要时阅读它。我想在Gameover类中使用这样的BufferedWriter和BufferedReader。
File fi = new File("score.txt");
BufferedWriter w = new BufferedWriter(new FileWriter(fi));
BufferedReader r = new BufferedReader(new FileReader(fi));
因此,每当我获得分数时,我都会将其与文件中的分数进行比较,如果分数更大,则文件的分数将作为高分子存储到文件中,因此新的高分将在文件中更新。但是问题是每次我运行程序时,score.txt都会获得零值,这意味着它没有存储上一个值,每次都会重置。也许是因为我正在使用新的文件撰稿人?我不知道该怎么做。
如果我使用(fi,true),则分数是这样存储的-04060100,这意味着第一行不会走任何地方只有行才能只能阅读第一行,高分不能是多个正确的吗?
该怎么办?我是Java中此文件存储系统的新手。
I am working on a game and I want to store the High score in a file and read it whenever it's needed. I wanted to use BufferedWriter and BufferedReader like this on the gameover class.
File fi = new File("score.txt");
BufferedWriter w = new BufferedWriter(new FileWriter(fi));
BufferedReader r = new BufferedReader(new FileReader(fi));
So whenever I get a score I will compare it to the score in the file and if the score is greater the score of the file I will store it to the file as a high score so the new high score will be updated in the file. But the problem is every time I run the program the score.txt got the null value, means it's not storing the previous value, it's just get reset every time. Maybe because I am using new FileWriter? I don't know how to do it.
If I use (fi, true), the score is storing like this - 04060100, that means the first line isn't going anywhere, all of the scores are writing in the first line only but I need to store the score in the first line only so that I can read the first line only, high score can't be multiple right?
What to do? I am new to this file storing system in Java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的...那是更清楚的对您试图做的事情的解释要比您在原始问题中写的内容。 (如果您在第一个瞬间就正确解释了它...)
解决方案是在您知道需要编写的文件之前,不要打开撰写文件的文件。逻辑应为:
您的代码当前要做的是在之前打开您甚至读取文件。这会截断文件,因此当您尝试读取当前高分时,信息已经被浪费了。
请注意,问题不是
BufferedWriter
bufferedReader 是问题所在。损坏是通过调用filewriter
构造函数来造成的。 (Javadoc应该解释它。)Yes ... that is a much clearer explanation of what you are trying to do than what you wrote in your original question. (If only you have explained it properly in the first instant ...)
The solution is to NOT open the file for writing until you know that it needs to be written. The logic should be:
What your code currently does is to open for writing before you even read the file. That truncates the file, so that when you try to read the current high score the information has already been trashed.
Note that it is not the
BufferedWriter
orBufferedReader
that is the problem. The damage is done by calling theFileWriter
constructor. (The javadoc should explain it.)