Let’s say you want to move a file or a folder to the recycle bin using java and not delete it permanently.
How can you do it?
Starting Java 9 , you can do it using a single line of code:
Desktop.getDesktop().moveToTrash()
Here is a demo:
I created a file under C:/files location using the below program:
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class TrashDemo { public static void main(String a[]) { try { Path f = Files.createFile(Path.of("C://files/newfile.txt")); } catch (IOException e) { e.printStackTrace(); } } }
And it got created as expected:

Then I moved it to trash using the below code:
import java.awt.Desktop; import java.nio.file.Path; public class TrashDemo { public static void main(String a[]) { Desktop.getDesktop().moveToTrash(Path.of("C://files/newfile.txt").toFile()); } }
And it was no longer in the original path.

It got moved to the recycle bin:

That’s it!
You can also move a folder to the recycle bin in the same way as done to a file.