0

I've recently made a Snake game with function that allows to store and find the best score of his. But unfortunetely it every time it saves your score into file, it deletes the previous file content. Is there any way to avoid that? As it is visible in the code below, I've made 3 methods. The first one is to save your score into a file. Last ones are to find the best score.

package matajus.snake;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Score {
private File file;
public static int score;
private static final String fileName = "BestScores.txt";

public Score() {
    file = new File(fileName);
    if(!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void saveToFile() throws FileNotFoundException {
    PrintWriter print = new PrintWriter(fileName);
    print.println(score);
    print.close();
}

public int findBestScore() {
    List<Integer> lines = new ArrayList<Integer>();
    Scanner input;
    int bestScore = 0;
    try {
        input = new Scanner(file);
        if(linesNumber() > 0) {
            for(int i = 0; i < linesNumber(); i++) {
                String readLine = input.nextLine();
                int line = Integer.parseInt(readLine);
                lines.add(line);
            }
            bestScore = Collections.max(lines);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return bestScore;
}

private int linesNumber() throws FileNotFoundException {
    BufferedReader reader = new BufferedReader(new FileReader(fileName));
    String line;
    int lines = 0;
    try {
        while((line = reader.readLine()) != null) {
            lines++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lines;
}
}

1 Answers1

0

PrintWritter will truncate the file: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.lang.String)

Have a look at the proposed solution here: How to append text to an existing file in Java

Mateusz Mrozewski
  • 2,151
  • 1
  • 19
  • 28