0

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 
3
  • Generally, you read the entire file into an application model at the beginning of your application and write the entire file from your application model at the end of your application. Commented Mar 13, 2023 at 14:53
  • Text files don't allow random access and insertions like this: You can only overwrite characters 1-to-1 (technically since variable-width-encodings like UTF-8 exists you can't even do that reliably). Basically most direct access that you want doesn't work for pure text files. Commented Mar 13, 2023 at 15:02
  • The simplest solution would be to have 1 file per mode instead of one shared one. Then you can simply overwrite that modes file each time. Commented Mar 13, 2023 at 15:03

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.