5

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);
        }
    }
Dr Mido
  • 2,414
  • 4
  • 32
  • 72

1 Answers1

3

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

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.

Here's the Reference

using JAVA :Use [com.sun.jna.platform.win32.W32FileUtils], which has moveToTrash and hasTrash methods defined.

Another ways is to use com.sun.jna.platform.FileUtils;

Sample code :

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");
    }
}
}
minigeek
  • 2,766
  • 1
  • 25
  • 35
  • this reference explains how to do that on C++ not in Java – Dr Mido Mar 07 '17 at 14:21
  • @DrMido Added Java part :) . Your question isn't duplicate still marked duplicate :/. If this satisfies as solution let me know :) – minigeek Mar 07 '17 at 14:28
  • minigeek I didn't vote negative for your comment, anyway can you edit your comment here "You can read about it " I cannot find the link for this bug – Dr Mido Mar 07 '17 at 14:46