0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Julien
  • 405
  • 2
  • 10
  • 21

3 Answers3

3

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.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
1

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.

Community
  • 1
  • 1
Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
1

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
}
GETah
  • 20,922
  • 7
  • 61
  • 103