我需要帮助在 Java 编程中删除然后重命名文件。我的问题是原始文件无法删除,第二个文件无法重命名。这是片段代码。任何建议将不胜感激。
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public void deleteLine(String content) {
try {
File inFile = new File("football.dat");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + "2");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true);
String linetobeempty = null;
while ((linetobeempty = br.readLine()) != null) {
if (!linetobeempty.trim().equals(content)) {
pw.println(linetobeempty);
pw.flush(); System.out.println(linetobeempty);
}
}
pw.close();
br.close();
boolean b = inFile.delete();
if (!b) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}