I have now written high scores to a text file at gameover, and read them at game load. The problem I have now is that the txt file highscores.txt isn't found anywhere because I haven't created it. Is it possible to have the file created whenever it isn't found? Here is the relevant code:
Write highscores to file at gameover:
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;
}
Read highscores from highscores.txt at program start:
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();
I know that I can create a file if it doesn't exist like this:
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("------------------------------------");
}
But I don't know how to do that with buffers. Please help!