1

I'm what I am trying to do is saving all the scores of a game, but it seems like it's just overwriting the first line and not adding them to the next line. I need your help! Thank you in advance!

System.out.print("Enter Your Name: ");
    String name = inputName.nextLine();

    try {
        File highscore = new File("highscore.txt");

        PrintWriter output = new PrintWriter(highscore);
        if (highscore.exists()) {
            System.out.println("Score has been saved!");
        }           
        output.println(name + " - " + score);
        output.close();

    } catch (IOException e) {
        System.out.println(e);
    }
}
kpAtCh
  • 97
  • 1
  • 8

3 Answers3

1

In order to open the file in append mode, you have to use FileWriter(String fileName, boolean appender) constructor.

output = new BufferedWriter(new FileWriter(file_name, true));

Add the above line and it should work.

Bush
  • 261
  • 1
  • 11
1

instead of

output.println()

use

output.append()

that should work...

Aurangzeb
  • 1,537
  • 13
  • 9
1

Use PrintWriter output = new PrintWriter(new FileWriter(highscore, true)); instead of PrintWriter output = new PrintWriter(highscore);

As the second argument in the constructor tells the FileWriter to append the input to the file rather than overwriting it.

 public class StreamFilter {

     public static void main(String[] args) {
         System.out.print("Enter Your Name: ");
         Scanner inputName = new Scanner(System.in);
         String score="hui";
         String name = inputName.nextLine();

            try {
                File highscore = new File("highscore.txt");

                PrintWriter output = new PrintWriter(highscore);//remove this
PrintWriter output = new PrintWriter(new FileWriter(highscore, true));//usethis,
                if (highscore.exists()) {
                    System.out.println("Score has been saved!");
                }           
                output.println(name + " - " + score);
                output.close();

            } catch (IOException e) {
                System.out.println(e);
            }
        }
    }
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46