将文件重命名为现有文件 java

Renaming file to existing file java

我正在尝试

  1. 创建临时文件"Temp Account Info.txt"
  2. 将现有帐户文件中的信息写入 "Account Information.txt" 至 "Temp Account Info.txt"
  3. 省略某些信息
  4. 删除"Account Information.txt"
  5. 将 "Temp Account Info.txt" 重命名为 "Account Information.txt"

我的问题是第 4 步和第 5 步。我也不确定我是否正确订购。 代码如下。

public static void deleteAccount(String accountNumber) throws Exception {
    File accountFile = new File("Account Information.txt");
    File tempFile = new File("Temp Account Info.txt");
    BufferedReader br = new BufferedReader(new FileReader(accountFile));
    FileWriter tempFw = new FileWriter(tempFile, true);
    PrintWriter tempPw = new PrintWriter(tempFw);

    String line;
    try {
        while ((line = br.readLine()) != null) {
            if(!line.contains(accountNumber)) {                    
                tempPw.print(line);
                tempPw.print("\r\n");
            }
        }
        **FileWriter fw = new FileWriter(accountFile);
        PrintWriter pw = new PrintWriter(fw);
        tempFile.renameTo(accountFile);
        accountFile.delete();
        fw.close();
        pw.close();
        tempFw.close();
        tempPw.close();
    } catch (Exception e) {
        System.out.println("ERROR: Account Not Found!");
    }
}

可在以下位置找到完整代码:https://hastebin.com/eposapecep.java

如有任何帮助,我们将不胜感激!

我知道我没有正确检查 "Account Not Found",我会在命名问题后尝试解决这个问题。

提前致谢!

使用文件的renameTo()方法。

   try {
        File file = new File("info.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

        String str = br.readLine();

        File file2 = new File("temp.txt");
        BufferedWriter bw = new BufferedWriter(new FileWriter(file2));

        bw.write(str);

        br.close();
        bw.close();
        if (!file.delete()) {
            System.out.println("delete failed");
        }
        if (!file2.renameTo(file)) {
            System.out.println("rename failed");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

上面的代码读取info.txt的第一行,写入temp.txt,删除info.txt,将temp.txt重命名为info.txt