I want to read a file containing high scores then add a new score and then finally rewrite the file with the rearranged top five scores. I'm not getting any errors but when I look at the file nothing has changed.
public synchronized void addHighScore(double s) {
FileReader in;
BufferedReader readFile;
FileWriter out;
BufferedWriter writeToFile;
double lowest = 0;
String previous[][] = new String[5][2];
String newScores[][] = new String[5][2];
try {
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
lowest = Double.parseDouble(readFile.readLine());
for (int i=0; i<5; i++) {
previous[i][0] = readFile.readLine();
previous[i][1] = readFile.readLine();
}
for (int i=0; i<5; i++) {
if (s>Double.parseDouble(previous[i][1])) {
if (i==0) {
continue;
} else {
newScores[i-1][0] = previous[i][0];
newScores[i-1][1] = previous[i][1];
if (i==1) {
lowest = Double.parseDouble(newScores[i-1][1]);
}
}
} else {
newScores[i-1][0] = "newPlayer";
newScores[i-1][1] = new Double(s).toString();
if (i==1) {
lowest = s;
}
for (int k=i; k<5; k++) {
newScores[i][0] = previous[i][0];
newScores[i][1] = previous[i][1];
}
break;
}
}
in.close();
readFile.close();
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
try {
out = new FileWriter(dataFile);
writeToFile = new BufferedWriter(out);
writeToFile.write(new Double(lowest).toString());
writeToFile.newLine();
for (int i=0; i<5; i++) {
writeToFile.write(newScores[i][0]);
writeToFile.newLine();
writeToFile.write(newScores[i][1]);
writeToFile.newLine();
}
out.close();
writeToFile.close();
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
The first line of the file is the lowest score value so that the whole file doesn't need to be read to know whether or not this method needs to be run. After the first line there are five sets of 2 lines with a name on the first and a score on the second.