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

£可爱£侵袭症+ 提交于 2019-12-10 23:03:49

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/42650298/how-to-move-files-dir-to-recycle-bin-in-java-instead-of-deleting-it-permanentl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!