我试着在我所做的游戏中记录一个高分:
PrintWriter out = new PrintWriter(new File("path"));
while(gameLoop) {
out.write(highScore);
out.flush();
}它一直将数据追加到文件的末尾。我知道我可以out.close();,然后是out = new PrintWriter(new File("path"));,但这似乎是很多多余的代码。不断关闭和重新打开文件,以实现覆盖。我的PrintWriter是否有任何方法可以覆盖数据而不关闭和重新打开文件?
发布于 2015-08-30 21:26:19
首先,我建议您将print (或println)与PrintWriter一起使用。接下来,如果我理解您的问题,您可以使用 Statement之类的
while (gameLoop) {
try (PrintWriter out = new PrintWriter(new File("path"))) {
out.println(highScore);
}
}它将在循环的每一次迭代中重新打开close和PrintWriter。或者,你可以使用nio和类似的东西
Path file = Paths.get("path");
while (gameLoop) {
byte[] buf = String.valueOf(highScore).getBytes();
Files.write(file, buf);
}https://stackoverflow.com/questions/32301271
复制相似问题