问题
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