How to move a file/folder to trash/Recyclebin in Java?

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s