java 使用jna 将文件删除到回收站

本文介绍了如何在Java中利用JNA库实现将文件安全删除至回收站的功能,包括相关的Maven依赖,并提及了Java 9之后提供的类似方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

maven 依赖:

	<dependency>
		<groupId>net.java.dev.jna</groupId>
		<artifactId>jna-platform</artifactId>
		<version>4.0.0</version>
	</dependency>

源代码:

package com.zhu.movetotrash;

import java.io.File;
import java.io.IOException;

import com.sun.jna.platform.FileUtils;

public class MoveToTrash {

    /**
     *
     * @param filePath
     * @return true on successful deletion of the file, filePath is null (or) empty.
     *         false in all other cases.
     */
    public static boolean moveFileToTrash(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            System.out.println("filePath shouldn't be null (or) empty");
            return true;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("File is not exist, seems to be it is already deleted");
            return true;
        }

        FileUtils fileUtils = FileUtils.getInstance();
        if (fileUtils.hasTrash()) {
            try {
                fileUtils.moveToTrash(new File[] { new File(filePath) });
                return true;
            } catch (IOException e) {
                System.out.println("Error while moving the file to trash " + e.getMessage());
                return false;
            }
        } else {
            System.out.println("No Trash available");
        }

        return true;
    }

    public static void main(String[] args) {

        String filePath = "e:/a.docx";

        boolean isFileMovedToTrash = moveFileToTrash(filePath);

        if (isFileMovedToTrash) {
            System.out.println("File is moved to trash " + filePath);
            return;
        }

        System.out.println("File is not moved to trash " + filePath);
    }
}

java 9 之后也出了类似的方法。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值