Julien
Julien

Reputation: 415

How to delete file on OSX from Java?

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

Answers (3)

GETah
GETah

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

jefflunt
jefflunt

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

Alexander Pogrebnyak
Alexander Pogrebnyak

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

Related Questions