怎么吧java删了,如何在Java中将文件/目录移动到回收站,而不是将其永久删除

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);

}

}

解决方案

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");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值