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?
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With