Java Buffered writer and file writer not writing to file

43 Views Asked by At

I am experimenting with java by building a commandline game. I want to save user progress to a file , and am using buffered writer as shown below but it does not write to file.What might be the issue?

//new added Player class

public class Player {
   public static String name="";
   public static int money=0;
   public static int level=1;
   public static int dragons=1;
   public static String difficulty="beginner";
   public static String mode="campaign";
   public static int numberofFights=0;
   public static int fightswon=0;
   public static int fightslost=0;
   

}

public void savePlayer() {
    System.out.println("Type 'save' to save game progress");
    if (scanner.nextLine().equals("save")) {
        try (BufferedWriter Bw = new BufferedWriter(new FileWriter("player.txt",true));) {
            System.out.println("Saving...");    // this is trped out as expected
            Bw.write(Player.name);
            Bw.newLine();
            Bw.write("" + Player.money);
            Bw.newLine();
            Bw.write("" + Player.level);
            Bw.newLine();
            Bw.write("" + Player.dragons);
            Bw.newLine();
            Bw.write(Player.difficulty);
            Bw.newLine();
            Bw.write(Player.mode);
            Bw.newLine();
            Bw.write("" + Player.numberofFights);
            Bw.newLine();
            Bw.write("" + Player.fightswon);
            Bw.newLine();
            Bw.write("" + Player.fightslost);
            Bw.newLine();
            Bw.flush();
            saveIsland();
        } catch (Exception e) {
            System.out.println(e);
        }
    } else {
        System.out.println("Wrong input please Try again");
        promptEnterKey();
        savePlayer();
    }

}
public void saveIsland() {
    try (BufferedWriter Bw = new BufferedWriter(new FileWriter("island.txt",true))) {
        Bw.write("" + Island.habitats);
        Bw.newLine();
        Bw.write("" + Island.farms);
        Bw.newLine();
        Bw.flush();
    } catch (Exception e) {
        

    }
}

Anyhelp will be appreciated

0

There are 0 best solutions below