如何在Java中将文件/目录移动到回收站,而不是将其永久删除 [英] How to move file(s)/dir to recycle bin in Java instead of deleting it permanently
问题描述
我正在尝试创建删除文件和/或目录的GUI示例,当用户单击Button时,但是我看到文件被永久删除,如何使其移动到回收站而不是此
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);
}
}
推荐答案
实际上,这是一个已引发但仍被忽略的错误,因为开发人员认为,如果添加了回收站功能,它就会won't be cross-platform-compatible
.您可以在 此处
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
使用 C ++ :但是您可以使用External APIs
.在JNI
的帮助下调用Windows SHFileOperation
API,在SHFILEOPSTRUCT
结构中设置FO_DELETE
标志.
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.
这是参考
使用 JAVA :使用[com.sun.jna.platform.win32.W32FileUtils
],其中已定义moveToTrash
和hasTrash
方法.
using JAVA :Use [com.sun.jna.platform.win32.W32FileUtils
], which has moveToTrash
and hasTrash
methods defined.
另一种方法是使用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");
}
}
}
这篇关于如何在Java中将文件/目录移动到回收站,而不是将其永久删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!