maven 依赖:
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>4.0.0</version>
</dependency>
源代码:
package com.zhu.movetotrash;
import java.io.File;
import java.io.IOException;
import com.sun.jna.platform.FileUtils;
public class MoveToTrash {
/**
*
* @param filePath
* @return true on successful deletion of the file, filePath is null (or) empty.
* false in all other cases.
*/
public static boolean moveFileToTrash(String filePath) {
if (filePath == null || filePath.isEmpty()) {
System.out.println("filePath shouldn't be null (or) empty");
return true;
}
File file = new File(filePath);
if (!file.exists()) {
System.out.println("File is not exist, seems to be it is already deleted");
return true;
}
FileUtils fileUtils = FileUtils.getInstance();
if (fileUtils.hasTrash()) {
try {
fileUtils.moveToTrash(new File[] { new File(filePath) });
return true;
} catch (IOException e) {
System.out.println("Error while moving the file to trash " + e.getMessage());
return false;
}
} else {
System.out.println("No Trash available");
}
return true;
}
public static void main(String[] args) {
String filePath = "e:/a.docx";
boolean isFileMovedToTrash = moveFileToTrash(filePath);
if (isFileMovedToTrash) {
System.out.println("File is moved to trash " + filePath);
return;
}
System.out.println("File is not moved to trash " + filePath);
}
}
java 9 之后也出了类似的方法。