Can I write only in certain lines in a file with BufferdWriter without overwrite others?

29 Views Asked by At

I want to save a highscore in a database, but if an sql-exeption is thrown I want to temporary save the data in a file. The game has diffent modes and for each there is a highscore. I would like to have a savefile like this:

2
Bob
4
Luca
6
Celina
9
Bob

Line 1 is the score for gamemode 1 and in line 2 there is the name of the player. Line 3 and 4 for gamemode 2 and so on.

I have this Java Code:

public static void saveHighscoreToDatabase(int spielModus, String nameHighscoretraeger, int score){
        try {
            Connection connection = DriverManager.getConnection(url, user, password);
            String sql = null;
            if (spielModus == 1){
                sql = "INSERT INTO HighscoreLeicht (`Name`, `Score`) VALUES (?,?)";
            }else if (spielModus == 2){
                sql = "INSERT INTO HighscoreMittel (`Name`, `Score`) VALUES (?,?)";
            }else if (spielModus == 3){
                sql = "INSERT INTO HighscoreSchwer (`Name`, `Score`) VALUES (?,?)";
            }else if (spielModus == 4){
                sql = "INSERT INTO HighscoreModus (`Name`, `Score`) VALUES (?,?)";
            }
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,nameHighscoretraeger);
            statement.setInt(2, score);
            statement.execute();
            connection.close();
        } catch (SQLException e) {
            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter("....SaveFile.txt",true));
                if (spielModus == 1){
                    bw.write(String.valueOf(score));
                    bw.newLine();
                    bw.write(nameHighscoretraeger);
                    bw.close();
                }else if (spielModus == 2){
                    bw.newLine();
                    bw.newLine();
                    bw.write(String.valueOf(score));
                    bw.newLine();
                    bw.write(nameHighscoretraeger);
                    bw.close();
                }else if (spielModus == 3){

                }else if (spielModus == 4){

                }
            }catch (Exception e2){
                System.out.println("Error");
            }
        }

The problem is, that the data of line 1 and 2 for example gets deleted if I want to save the data for line 3 and 4.

I tried using "newLine()" to skip the lines I'm already using, but then the data from those lines gets deleted. For example if I want to save the score 4 with the name Luca (line 3 and 4) the score of the gamemode 1 (2 and Bob, line 1 and 2) gets deletetd.

<blank>  
<blank>   
4
Luca
0

There are 0 best solutions below