0

why this code dont work correct? file a.txt is create on hard disk and then a.txt rename to b.txt but b.txt will not delete.

import java.io.File;

public class Main {

    public static void main(String[] args) {

        File f=new File("a.txt");
        try {

            f.createNewFile();
        }
        catch (Exception e){}

        f.renameTo(new File("b.txt"));

        f.delete();
    }
}

If the line

f.renameTo(new File("b.txt"));

is removed, f.delete(); works correctly and a.txt is deleted from hard disk.

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
  • You should log more info and not hidding Exception. Try closing the file "b.txt". Extrernalize b File b=new File("b.txt"). Also you could test file existence before delete... – Xavier Bouclet Nov 07 '17 at 17:20
  • file "b.txt" is closed and exist on hard but not delete.. – Hamid Matin Nov 07 '17 at 17:31
  • So like Hamid said I would try to see if another process is locking the file. But provide more info. It's hard to tell without any error. – Xavier Bouclet Nov 07 '17 at 17:44

1 Answers1

0

The delete method will not work if :

  • The file doesn't exist
  • The file is open by another process (editor, ..)
  • You dont't have privileges to delete it.

Could you provide the error stack to analyze?

losusovic
  • 608
  • 5
  • 22