java - 文件拒绝重命名
问题描述
我一直在尝试将新数据写入文件,但它拒绝重命名文件,这导致文件在我的代码末尾不会被覆盖和删除:
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 文件提供了正确的目录以覆盖正确的文件?
解决方案
您打开fw
时tempFile
打开它,您不能在所有操作系统(尤其是 Windows)上重命名或删除它。
我建议您使用 try-with-resource 并始终在尝试重命名或删除文件之前关闭文件。
BTWnew 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();
}
}
我不知道你是否需要调试线路。
推荐阅读
- vue.js - 如何在 Nativescript Vue RadDataForm 中实现分组?
- machine-learning - OpenAI gym breakout-ram-v4 无法学习
- docker - Filebeat 7.2 - 将日志从 Docker 容器保存到 Logstash
- java - 错误:任务“:app:transformClassesWithJarMergingForDebug”执行失败。> com.android.build.api.transform.TransformException
- python - 将 Qt 嵌入本机窗口 (Windows)
- python - tf.nn.in_top_k(logits,y,1) 超出范围错误但实际上相等
- electron - 带有 Nex.js 的电子应用程序(加载 html 文件不起作用)
- python - 点击后如何删除tkinter中的消息
- android - ViewGroup中绘制背景drawable的方式
- swift - 无法使用 SCNLight 出现阴影