beaTunes News

Thursday, May 21, 2009

Moving files to the Windows Recycling Bin in Java

beaTunes2 logoThis is a little random and has little to do with beaTunes. However, I thought I share...

As you may know, there is no way to move files to the Windows Recycling Bin in Java (instead of simply deleting them). It is however actually not very hard. All you need to do, is get a reference to a Shell object and use it to move your file. Now how do you get that Shell object? The easiest way is probably COM4J. The shell32 typelib id is 50a7e9b0-70ef-11d1-b75a-00a0c90564fe. Use it to generate some stubs. Then you simply write something like this:

final IShellDispatch shell = ClassFactory.createShell();
// you might want to make sure your parent path has back slashes!
final Folder fileFolder = shell.nameSpace(file.getParent());
final FolderItem fileItem = fileFolder.parseName(file.getName());
final Folder folder = shell.nameSpace(ShellSpecialFolderConstants.ssfBITBUCKET);
folder.moveHere(fileItem, null);

This assumes that file is the file you want to move to the trash.

That's it.

BTW: On OS X you can simply call AppleScript with something like tell application "Finder" to delete Posix File "<your filename here>" - it'll move your file to the trash.


Post a Comment

<< Home