I've been trying to write new data to a file but it refuses to rename the file, which causes the file to not be overwritten and deleted at the end of my code:
private URL gameHistoryURL = Game.class.getClassLoader().getResource("Files/GameHistory.csv");
private String gameHistoryPath = gameHistoryURL.getPath();
protected void writeToGameHistory(int game) {
String tempFile = "temp1.txt";
File oldFile = new File(gameHistoryPath);
File newFile = new File(tempFile);
try {
FileWriter fw = new FileWriter(tempFile);
FileReader fr = new FileReader(tempFile);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
LineNumberReader count = new LineNumberReader(fr);
s = new Scanner(new File(gameHistoryPath));
String gameName;
int lineNum = count.getLineNumber() + 1;
//Skip the first line if line number is 10
if (lineNum >= 10) {
s.nextLine();
}
while (s.hasNext()) {
String x = s.nextLine();
pw.println(x);
}
switch (game) {
case 1: {
pw.println("Game1");
break;
}
case 2: {
pw.println("Game2");
break;
}
case 3: {
pw.println("Game3");
break;
}
}
s.close();
pw.flush();
pw.close();
File f = new File(gameHistoryPath);
oldFile.delete();
newFile.renameTo(f);
System.out.println(newFile + " " + gameHistoryPath);
}
catch (Exception e) {
System.out.println("Error: " + e);
}
}
The print lines in the try method simply return:
temp1.txt [File Path]/Files/GameHistory.csv
How can I make sure that the temp1.txt file is given the correct directory to overwrite the correct file?