Home > Mobile >  I cant delete old file and rename new file Java
I cant delete old file and rename new file Java

Time:03-28

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[];
    del = id.getText();
    File old = new File("record.txt");
    File new = new File("temp.txt");
    
    try{
        FileWriter a = new FileWriter("temp.txt",true);
        BufferedWriter e = new BufferedWriter(a);
        PrintWriter b = new PrintWriter(e);
        
        FileReader c = new FileReader("record.txt");
        BufferedReader d = new BufferedReader(c);
        
        while((current = d.readLine()) != null){
            data = current.split("~");
            if(!(data[0].equalsIgnoreCase(del))){
            b.println(current);
            }
    }
        b.flush();
        b.close();
        c.close();
        d.close();
        e.close();
        a.close();
        
        old.delete();
        new.renameTo(old);
        
        JOptionPane.showMessageDialog(this, "Record is 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

CodePudding user response:

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.

  • Related