我一直在尝试向文件中写入新数据,但是它拒绝重命名文件,这导致文件在我的代码末尾不会被覆盖和删除:
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);
}
}
try方法中的打印行仅返回:
temp1.txt [File Path]/Files/GameHistory.csv
如何确保给temp1.txt文件正确的目录以覆盖正确的文件?
答案 0 :(得分:0)
您以fw
的身份打开tempFile
的同时,不能在所有操作系统(尤其是Windows)上重命名或删除它。
我建议您使用try-with-resource,并在尝试重命名或删除文件之前始终关闭文件。
BTW new FileWriter(tempFile);
会截断该文件,因此如果您尝试读取它,它将始终为空。
此方法的目的似乎是在文件末尾追加一行以记录每个游戏的进行情况。
protected void writeToGameHistory(int game) {
// create a new file, or append to the end of an existing one.
try (PrintWriter pw = new PrintWriter(new FileWriter(gameHistoryPath, true))) {
pw.println("Game" + game);
System.out.println(gameHistoryPath + " added Game" + game);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
我不知道您是否需要调试线路。