'Cannot Delete .txt File

I want to to make program that delete the Trainer.txt and replace it with Temp.txt and rename it to Trainer.txt. So the whole code is about deleting specific line based on the TrainerIDText. The temp file is successfully created without the deleted information inside.

Image of Trainer.txt and Temp.txt

    Scanner x;
    String removeTerm=TrainerIDText.getText();
    String filepath = "C:\\Users\\enric\\OneDrive\\Desktop\\Assignment.txt\\Trainer.txt";
    
    String tempFile = "C:\\Users\\enric\\OneDrive\\Desktop\\Assignment.txt\\Temp.txt";
    File oldFile = new File(filepath);
    File newFile = new File(tempFile);
    String ID = "" ; String name = "" ; String ic = "" ; String dob = "" ; String address = "" ;String contact = "" ; String specialization = "" ;
    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();
            ic = x.next();
            dob =x.next();
            address = x.next();
            contact = x.next();
            specialization = x.next();
            if(!ID.equals(removeTerm))
            {
                pw.println(ID+","+name+","+ic+","+dob+","+address+","+contact+","+specialization);
            }
        }
        
        x.close();
        pw.flush();
        pw.close();
        oldFile.delete();
        File dump = new File(filepath);
        newFile.renameTo(dump);
        JOptionPane.showMessageDialog(null,"Information Deleted");

    }
    catch(Exception e)
    {
        JOptionPane.showMessageDialog(null,"Error"+removeTerm);
    }
        
    

The problem is that the Trainer.txt file is not deleting and the Temp.txt file is not changing name to Trainer.txt. Anyone know the issue or solution?



Sources

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

Source: Stack Overflow

Solution Source