Reputation: 2730
I have a method to delete a line on a text file which will contain a selected phone number. below is my code.
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String selectedphone = Phone.getText();
BufferedReader br = new BufferedReader(new FileReader(file));
// Construct the new file that will later be renamed to the original file
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (line.trim().startsWith(selectedphone)) {
continue;
} else {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
file.delete();
if (!file.delete()) {
System.out.println("Could not delete file");
}
//rename tempphonebook.txt file back to phonebook.txt
tempFile.renameTo(file);
if (tempFile.renameTo(file)) {
System.out.println("Update succesful");
} else {
System.out.println("Update failed");
}
} catch (Exception e) {
}
}
my 'phonebook.txt' file is as below
0787465147|John|Doe|924578654v|Colombo|
0715435786|Jane|Doe|6672475845v|Colombo|
0114745755|Foo|Baz|6454753754v|Kandy|
And when I click 'delete' button with a 'selectedphone' as 0787465147 it will create a 'tempphonebook.txt' file as below.
0715435786|Jane|Doe|6672475845v|Colombo|
0114745755|Foo|Baz|6454753754v|Kandy|
Then the 'phonebook.txt' should be deleted and the 'tempphonebook.txt' should be renamed to 'phonebook.txt'. problem is I'm unable to delete the 'phonebook.txt' file. I get this massage when I click the 'delete' button
Could not delete file
Update failed
can someone please help me with this? Thanks in advance! :)
Upvotes: 3
Views: 8434
Reputation: 11651
Use try-with-resources. This works in most of the cases
And yes remove the extra code for delete and renaming the file.
You just need to use fileName.delete() or fileName.renameTo("name"); once. If the command is successful it will return true.
When you use the command again, it will try to delete the file which does not exists(you have already deleted this).
See this example Deleting Lines on text file
It deals with a similar problem.
Upvotes: -2
Reputation: 172458
Your code is trying to delete the file twice. So if the file is deleted at the first attempt your second call becomes invalid. You need to remove the first one
//file.delete(); //not required
if (!file.delete()) {
Upvotes: 2
Reputation: 69450
You try to delete the file twice:
file.delete();
if (!file.delete()) {
remove the first file.delete();
Upvotes: 3