Is it possible with Java to delete to the Recycle Bin?
Java 9 has new method but in my case I am restricted to Java 8. I found Java Native Access Platform that has hasTrash() and moveToTrash() method. I tested it on Win 10 and Mac OS (Worked) for me.
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 Repository https://mvnrepository.com/artifact/net.java.dev.jna/jna-platform/5.1.0
Don't confuse It is Java Native Access Platform not Java Native Access
I have found this RFE on suns site: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5080625
This tells me there is not a native java way to do this. and as @John Topley just posted the only solution is a JNI call.
Ten years later, with Java 9, finally there is a builtin way to move files to the Trash Bin
java.awt.Desktop.moveToTrash(java.io.File)
:
public boolean moveToTrash(File file)
Moves the specified file to the trash.
Parameters:
file - the file
Returns:
returns true if successfully moved the file to the trash.
The availability of this feature for the underlying platform can be tested with Desktop.isSupported(Desktop.Action.MOVE_TO_TRASH)
.
For various reasons Windows has no concept of a folder that simply corresponds to the Recycle Bin.
The correct way is to use JNI to invoke the Windows SHFileOperation
API, setting the FO_DELETE
flag in the SHFILEOPSTRUCT
structure.
- SHFileOperation documention
- Java example for copying a file using SHFileOperation (the Recycle Bin link in the same article doesn't work)