'I cant delete old file and rename new file Java

After I move all the line except one i want to delete, the old text file should be delete but it don't.

String del, current, data[];
delete = code.getText();
File old = new File("record.txt");
File new = new File("temp.txt");

try {
    FileWriter z = new FileWriter("temp.txt",true);
    BufferedWriter y = new BufferedWriter(z);
    PrintWriter q = new PrintWriter(y);
    
    FileReader f = new FileReader("record.txt");
    BufferedReader d = new BufferedReader(f);
    
    while((current = d.readLine()) != null) {
        data = current.split("~");
        if(!(data[0].equalsIgnoreCase(delete))) {
            q.println(current);
        }
    }
    q.flush();
    q.close();
    f.close();
    d.close();
    y.close();
    z.close();
    
    old.delete();
    new.renameTo(old);
    
    JOptionPane.showMessageDialog(this, "Deleted");
} catch(IOException e) {
}

i have also using Files.delete(path); also don't work

the old.delete() do not function. how to solve it

-- AH i see, i didnt close for others function .Thx



Solution 1:[1]

You use File.delete() to delete the file - but you do not check the return code. Read about File.delete() and File.deleteOnExit().

Altogether, you need to anticipate errors and define the behaviour of your application. As @k314159 pointed out already, catching exceptions and not doing something means you hide errors - no wonder you may get confused when your application misbehaves.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1