Reputation: 415
I try to delete a file on OSX via Java and it doesn't work.
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "/bin/bash", "-c", "rm file.pdf" });
Any idea?
Upvotes: 0
Views: 1141
Reputation: 21409
You can do this to delete your file.
try{
File f1 = new File("path to file");
boolean success=f1.delete();
if(!success){
// Notify user that the file
}
}catch(SecurityException ex){
// No sufficient rights to do this operation
}
Upvotes: 1
Reputation: 33954
You don't need to execute a shell command to do this. In fact, using a shell command to do this will make your app platform-specific, rather than platform-independent.
Simply create a reference to the file, and call the delete() method:
File fileToDelete = new File("/path/to/file").delete();
There are also methods on the File class that allow you to create temporary files.
The delete on exit functions should be avoided, as noted by Alexander's comment, and this bug/proposed fix on the Oracle support pages.
NOTE: All file access (reading, writing, deleting) is run through a SecurityManager, so if the user under which your application is running doesn't have the necessary security rights to the file in question, these operations may fail. If you simply keep your app running in user space, are only accessing files that the user has access to, or are only dealing with temporary files, you should be fine.
Upvotes: 3
Reputation: 45576
As normalocity had mentioned java.io.File
class has a method to delete a file
For fancier file/directory operations you may want to check out FileUtils from apache.
Upvotes: 1