Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 'file.delete()' Is not Deleting Specified File

This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.

UserInput.prompt("Enter name of file to delete"); String name = UserInput.readString(); File file = new File("\\Files\\" + name + ".txt"); file.delete(); 

Any help would be GREATLY appreciated!

I now have:

File file = new File(catName + ".txt"); String path = file.getCanonicalPath(); File filePath = new File(path); filePath.delete(); 

To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.

like image 445
Kimberley Lloyd Avatar asked Dec 19 '10 23:12

Kimberley Lloyd


People also ask

How do you delete a specific file in Java?

In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete.

How do you force delete a file that won't delete?

One is simply using the delete option, and the other one is deleting files permanently. When you can't delete a file normally, you can delete undeletable files Windows 10 by selecting the target file or folder and then press Shift + Delete keys on the keyboard for a try.

How do I delete a file using Java NIO?

In Java, we can use the NIO Files. delete(Path) and Files. deleteIfExists(Path) to delete a file.


1 Answers

The problem could also be due to any output streams that you have forgotten to close. In my case I was working with the file before the file being deleted. However at one place in the file operations, I had forgotten to close an output stream that I used to write to the file that was attempted to delete later.

like image 127
user2926391 Avatar answered Sep 22 '22 03:09

user2926391