Friday 6 January 2017

Move files to recycle bin (or) trash

Some time when you are working with applications that performs CRUD operations on files, you need to move a file/folder to recycle bin rather than deleting permanently. By using ‘com.sun.jna.platform.FileUtils’ class, we can move a file/folder to recycle bin.

I used following maven dependency.

                 <dependency>
                          <groupId>net.java.dev.jna</groupId>
                          <artifactId>jna-platform</artifactId>
                          <version>4.0.0</version>
                 </dependency>

MoveToTrash.java
import java.io.File;
import java.io.IOException;

import com.sun.jna.platform.FileUtils;

public class MoveToTrash {

 /**
  * 
  * @param filePath
  * @return true on successful deletion of the file, filePath is null (or)
  *         empty. false in all other cases.
  */
 public static boolean moveFileToTrash(String filePath) {
  if (filePath == null || filePath.isEmpty()) {
   System.out.println("filePath shouldn't be null (or) empty");
   return true;
  }

  File file = new File(filePath);
  if (!file.exists()) {
   System.out.println("File is not exist, seems to be it is already deleted");
   return true;
  }

  FileUtils fileUtils = FileUtils.getInstance();
  if (fileUtils.hasTrash()) {
   try {
    fileUtils.moveToTrash(new File[] { new File(filePath) });
    return true;
   } catch (IOException e) {
    System.out.println("Error while moving the file to trash " + e.getMessage());
    return false;
   }
  } else {
   System.out.println("No Trash available");
  }

  return true;
 }

 public static void main(String[] args) {

  String filePath = "C:\\Users\\Proxy.docx";
  
  boolean isFileMovedToTrash = moveFileToTrash(filePath);
  
  if(isFileMovedToTrash){
   System.out.println("File is moved to trash " + filePath);
   return;
  }
  
  System.out.println("File is not moved to trash " + filePath);
 }
}

After running above application, it deletes the file "C:\\Users\\Proxy.docx" and move it to recycle bin on windows and to trash on Mac.

You may like


No comments:

Post a Comment