Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete file at location using Java

Tags:

java

Given a string location and string file name, is it possible to execute a java command to delete said file? If so, what package or class should I look at using for this?


2 Answers

Using the file's string location and name, get a file handle for it:

File doomedFile = new File (location, name);
doomedFile.delete();

Note that you should encapsulate this with appropriate code to catch potential problem cases, such as if Java does not have the permission to delete that file on your current system. Or, if the file isn't found or another, similar, edge case.

The API you want to look at in this case is java.io.File. Note that while this function returns a bool indicating whether the action succeeded, it might also throw a SecurityException if the user does not have permission to take the action.

like image 126
Nathaniel Ford Avatar answered Oct 16 '25 23:10

Nathaniel Ford


You can use this code:

File fileToDelete= new File(yourPath, fileName);
if(fileToDelete.delete()){
  System.out.println("File deleted");
} else {
  System.out.println("Operation failed");
}
like image 20
KIBOU Hassan Avatar answered Oct 16 '25 22:10

KIBOU Hassan