Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a text file in java

Tags:

java

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! :)

like image 542
P. K. Tharindu Avatar asked Jun 09 '26 20:06

P. K. Tharindu


1 Answers

You try to delete the file twice:

    file.delete();
    if (!file.delete()) {

remove the first file.delete();

like image 59
Jens Avatar answered Jun 11 '26 11:06

Jens