我正在写一个"删除"文本文件中的一行。如何删除原始文件并重命名新文件失败。
会发生什么,它会在文件名" temp.txt"下保存我要保存的行。但它应该做的是删除原始文件(TaskList.txt)然后将temp.txt重命名为TaskList.txt任何人都可以帮忙吗?这是我的代码:
import java.io.*;
import java.io.File;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
import java.awt.event.*;
class DeleteTask implements ActionListener{
private static Scanner x;
JFrame frame;
JButton deleteButton;
JTextField delete;
JLabel label;
public void completedTask()
{
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setTitle("Delete Task");
delete = new JTextField(10);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(this);
label = new JLabel ("Enter task name");
frame.add(label,BorderLayout.WEST);
frame.add(delete,BorderLayout.CENTER);
frame.add(deleteButton,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
String filePath = "TaskList.txt";
String removeTerm= delete.getText();
removeRecord(filePath,removeTerm);
frame.dispose();
}
public static void removeRecord(String filePath, String removeTerm)
{
String tempFile = "temp.txt";
File oldFile = new File(filePath);
File newFile = new File(tempFile);
String id = "" ; String name = "" ; String age = ""; String descript = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while(x.hasNext())
{
id = x.next();
name = x.next();
age = x.next();
descript = x.next();
if(!id.equals(removeTerm))
{
pw.println(id + ", " + name + ", " + age + ", " + descript);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E)
{
}
}
}