Java在这里是关键。我需要能够删除文件,但用户希望能够从回收站“还原”。就我所知,这似乎不可能。有人知道吗?
java.awt.Desktop.moveToTrash(java.io.File)
方法可以实现。
可通过
public boolean moveToTrash(File file)
将指定的文件移动到回收站。
参数:
file - 文件
返回值:
如果成功将文件移动到回收站,则返回 true。
Desktop.isSupported(Desktop.Action.MOVE_TO_TRASH)
测试底层平台是否支持此功能。由于各种原因,Windows没有与回收站相对应的文件夹概念。
正确的方法是使用JNI调用Windows的SHFileOperation
API,在SHFILEOPSTRUCT
结构中设置FO_DELETE
标志。
我需要使用Java 8,但是Java 9有新的方法。我发现了Java Native Access Platform,它有hasTrash()和moveToTrash()方法。我在Win 10和Mac OS上进行了测试(对我来说有效)。
static boolean moveToTrash(String filePath) {
File file = new File(filePath);
FileUtils fileUtils = FileUtils.getInstance();
if (fileUtils.hasTrash()) {
try {
fileUtils.moveToTrash(new File[] { file });
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
System.out.println("No Trash");
return false;
}
}
Maven仓库 https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform/5.1.0
不要混淆,这是Java Native Access Platform而不是Java Native Access
我的建议是使用cmd工具Recycle.exe,并加上-f参数来强制回收(无需提示)。完美运行。
public class Trash {
public void moveToTrash(File ... file) throws IOException {
moveToTrash(false, file);
}
public void promptMoveToTrash(File ... file) throws IOException {
moveToTrash(true, file);
}
private void moveToTrash(boolean withPrompt, File ... file) throws IOException {
String fileList = Stream.of(file).map(File::getAbsolutePath).reduce((f1, f2)->f1+" "+f2).orElse("");
Runtime.getRuntime().exec("Recycle.exe "+(withPrompt ? "" : "-f ")+fileList);
}
}
FileUtils
不使用Win32 API。您应该选择支持撤消(从回收站还原文件)的W32FileUtils
。
编辑:截至当前JNA平台(5.7.0)的版本,通过FileUtils.getInstance(),此语句已经不正确,并且FileUtils将使用Win32 API。
FOF_ALLOWUNDO
执行删除文件的默认操作。 - Paul LammertsmaSHFileOperation
的内容都无法在 OS X 上运行,因为SHFileOperation
是 Windows 的 API。 - John Topley