Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move file(s)/dir to recycle bin in Java instead of deleting it permanently [duplicate]

I am trying to create example of GUI that's delete files and/or directories When user clicks on Button, but I see that files deleted permanently, How to make it moves to recycle bin instead of this

  if (File_path.getText().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Please select a file or directory", "Info", JOptionPane.INFORMATION_MESSAGE);
    } else {
        File FileName = new File(File_path.getText());
        boolean FileDeleted = FileName.delete();
        if (FileDeleted == true) {
            JOptionPane.showMessageDialog(null, "File Deleted Successfully", "Info", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "File Not Found", "Info", JOptionPane.INFORMATION_MESSAGE);
        }
    }
like image 615
Dr Mido Avatar asked Oct 18 '22 16:10

Dr Mido


1 Answers

Actually, it is a bug fired but neglected because developers believe it won't be cross-platform-compatible if move to recycle bin functionality added. You can read about it here

using C++ : But you can do with External APIs. With the help of JNI to invoke the Windows SHFileOperation API, setting the FO_DELETE flag in the SHFILEOPSTRUCT structure.

Here's the Reference

using JAVA :Use [com.sun.jna.platform.win32.W32FileUtils], which has moveToTrash and hasTrash methods defined.

Another ways is to use com.sun.jna.platform.FileUtils;

Sample code :

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

import com.sun.jna.platform.FileUtils;

public class MoveToTrash {

  public static void main(String[] args){
    FileUtils fileUtils = FileUtils.getInstance();
    if (fileUtils.hasTrash()) {
        try {
            fileUtils.moveToTrash( new File[] {new File("c:/folder/abcd.txt") });                
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    else {
        System.out.println("No Trash available");
    }
}
}
like image 98
minigeek Avatar answered Oct 21 '22 04:10

minigeek