如何将文件/目录移动到 Java 中的回收站而不是永久删除它

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

我正在尝试创建删除文件 and/or 目录的 GUI 示例当用户单击按钮时,但我看到文件被永久删除,如何使其移动到回收站而不是这个

  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);
        }
    }

实际上,这是一个被触发但被忽略的错误,因为开发人员认为它 won't be cross-platform-compatible 如果添加了回收站功能。你可以阅读它 here

使用 C++ :但是您可以使用 External APIs。借助 JNI 调用 Windows SHFileOperation API,在 SHFILEOPSTRUCT 结构中设置 FO_DELETE 标志。

这是Reference

using JAVA:使用[com.sun.jna.platform.win32.W32FileUtils],其中定义了moveToTrashhasTrash方法。

另一种方法是使用com.sun.jna.platform.FileUtils;

示例代码:

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");
    }
}
}