1

I am trying to delete a file: This is the code and I can't see anything wrong

System.out.println("users//"+"user"+i.getId());
            File f=new File("users//"+"user"+i.getId());
            System.out.println("Can READ: "+f.canRead());
            System.out.println("Can WRITE: "+f.canWrite());
            System.out.println("Can EXEC: "+f.canExecute());
            System.out.println("Exists: "+f.exists());
            System.out.println(f.delete());

Yes, I have the right to read,write,exec and the file exists. I don't have any exceptions

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 4
    What exactly is the problem you are facing? – akhil_mittal May 11 '15 at 13:51
  • Sometimes, even though you have the right, you need to start/execute the `.jar`, or in case of development the IDE saying `Eclipse` or `Netbeans` or whatever as Administrator / in Administrator Mode – Loki May 11 '15 at 13:52
  • 1
    well ..it does nothing. doesn't remove the file – Ioana Geanta May 11 '15 at 13:52
  • From http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java you can see different solutions for this. – Mihai8 May 11 '15 at 13:56
  • why are you doing this : `System.out.println(f.delete());` Try : `f.delete();` instead – Akash Rajbanshi May 11 '15 at 13:56
  • You're probably not trying to delete the file you think you're deleting. Print f.getAbsolutePath() to find out what you're trying to delete. – aioobe May 11 '15 at 13:57
  • 1
    [Don't use File in 2015](http://java7fs.wikia.com/wiki/Why_File_sucks). Use java.nio.file. – fge May 11 '15 at 13:59

2 Answers2

3

I have tried this code and it works:

public static void main(String[] args) {
        try {
            File file = new File("c:\\Users\\Akhil\\logfile11052015.log");
            if (file.delete()) {
                System.out.println("Success: " + file.getName() + " is deleted!");
            } else {
                System.out.println("Failed: Delete operation is failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

May be you can check if you are providing correct path in your case and file exists there.

Output: Success: logfile11052015.log is deleted!

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
-1

I needed to call System.gc() after the remove.

spongebob
  • 8,370
  • 15
  • 50
  • 83