【发布时间】:2015-10-22 21:14:01
【问题描述】:
我现在在游戏结束时将高分写入文本文件,并在游戏加载时读取它们。我现在遇到的问题是 txt 文件 highscores.txt 在任何地方都找不到,因为我还没有创建它。是否可以在找不到文件时创建文件?以下是相关代码:
在游戏结束时将高分写入文件:
if(gameOver == true){
sbg.enterState(5, new FadeOutTransition(), new FadeInTransition());
if(score > Highscores.highscore3 && score < Highscores.highscore2){
Highscores.highscore3 = score;
}else if(score > Highscores.highscore2 && score < Highscores.highscore1){
Highscores.highscore3 = Highscores.highscore2;
Highscores.highscore2 = score;
}else if(score > Highscores.highscore1){
Highscores.highscore3 = Highscores.highscore2;
Highscores.highscore2 = Highscores.highscore1;
Highscores.highscore1 = score;
}else Highscores.highscore1 = score;
//Write highscores to highscores.txt
try{
PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
writer.println(String.valueOf(Highscores.highscore1));
writer.println(String.valueOf(Highscores.highscore1));
writer.println(String.valueOf(Highscores.highscore1));
writer.close();
}catch(Exception e){
e.printStackTrace();
}
gameOver = false;
gameStart = false;
}
在程序开始时从 highscores.txt 中读取高分:
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new FileReader("highscores.txt"));
String line;
while((line = in.readLine()) != null){
System.out.println(line);
}
in.close();
我知道如果文件不存在,我可以创建一个这样的文件:
try{
File save = new File("highscores.txt");
if (!save.exists()){
save.createNewFile();
System.out.println("\n----------------------------------");
System.out.println("The file has been created.");
System.out.println("------------------------------------");
}
但我不知道如何使用缓冲区来做到这一点。请帮忙!
【问题讨论】:
-
我忘了提到有一个 Highscores 类,它包含 highscore1、highscore2 和 highscore3 整数,供所有其他类取用。
-
你也可以添加高分类吗?
-
请不要粘贴。相关代码必须在问题本身中。只需删除所有不相关的代码 - 当为这个问题按下按钮时,你所做的并不真正相关。
-
对不起各位,第一次来这里:')
标签: java file save lwjgl slick2d