首页 > 解决方案 > 文件拒绝重命名

问题描述

我一直在尝试将新数据写入文件,但它拒绝重命名文件,这导致文件在我的代码末尾不会被覆盖和删除:

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 文件提供了正确的目录以覆盖正确的文件?

标签: javafile

解决方案


您打开fwtempFile打开它,您不能在所有操作系统(尤其是 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();
    }
}

我不知道你是否需要调试线路。


推荐阅读