pranjalshah.ps
pranjalshah.ps

Reputation: 55

Why is a file not getting deleted using the file.delete() function?

I am using a method to delete a particular pre-existing file using the file.delete() method as follows

public void deleteFile(String fileName)throws IOException  //To refine. Does not work
{
    File file=new File("C:\\File Handling\\"+fileName+".txt");
    boolean success=file.delete();
    System.out.println(success);
}

However success is always returned as false. What is going wrong?

Please advise on how else to delete a file using java.

Upvotes: 1

Views: 160

Answers (3)

Cody Anderson
Cody Anderson

Reputation: 124

Sometimes windows can be funky about how it handles files try using the method deleteOnExit() method that way you can make sure that the program isn't still open inside your code. Also did you double check that the file isn't open in a different program before running the code?

Upvotes: 0

Shrinath
Shrinath

Reputation: 564

Your code works perfectly fine on my machine. I just wrapped it in a class and made it static to be called by main()

public static void main(String[] args) throws IOException {
        deleteFile("newfile");
    }

    public static void deleteFile(String fileName)throws IOException  //To refine. Does not work
    {
        File file=new File("C:\\File Handling\\"+fileName+".txt");
        boolean success=file.delete();
        System.out.println(success);
    }

Upvotes: 1

b4hand
b4hand

Reputation: 9770

On Windows you typically can't delete files that are opened by any process. Also you may want to check if you have permissions by doing the delete from the command line.

Upvotes: 1

Related Questions