删除文件踩的坑

踩坑的点:

我删除文件的方式,一开始,为了方便,使用了

file.deleteOnExit();
这种方式,还顺便判断了一下,只有文件存在是时候才删除,省的多写一步 判空操作,但是,闲来无事的时候,做了个测试,因为发现cpu 有的时候占用率比较高

翻翻源码

/**
 * Requests that the file or directory denoted by this abstract
 * pathname be deleted when the virtual machine terminates.
 * Files (or directories) are deleted in the reverse order that
 * they are registered. Invoking this method to delete a file or
 * directory that is already registered for deletion has no effect.
 * Deletion will be attempted only for normal termination of the
 * virtual machine, as defined by the Java Language Specification.
 *
 * <p> Once deletion has been requested, it is not possible to cancel the
 * request.  This method should therefore be used with care.
 *
 * <P>
 * Note: this method should <i>not</i> be used for file-locking, as
 * the resulting protocol cannot be made to work reliably. The
 * {@link java.nio.channels.FileLock FileLock}
 * facility should be used instead.
 *
 * @throws  SecurityException
 *          If a security manager exists and its <code>{@link
 *          java.lang.SecurityManager#checkDelete}</code> method denies
 *          delete access to the file
 *
 * @see #delete
 *
 * @since 1.2
 */

public void deleteOnExit() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkDelete(path);
    }
    if (isInvalid()) {
        return;
    }
    DeleteOnExitHook.add(path);
}

注释的意思是说,这个文件只有在虚拟机停止的时候,才会被删除,那正常来说我的虚拟机肯定是一直活在的,挂了那就得加班改bug 了呀,所以,这个方法只是相当于把文件加到了一个队列(DeleteOnExitHook.add(path)) ,需要被删除,但是并没有被立即删除

/**
 * This class holds a set of filenames to be deleted on VM exit through a shutdown hook.
 * A set is used both to prevent double-insertion of the same file as well as offer
 * quick removal.
 */

class DeleteOnExitHook {...}

这个类的注释说的清清楚楚,这类持有一些文件名,需要在虚拟机退出的时候,通过运行钩子函数删除图片:

就是指的runHooks 这个方法,所以,如果是想立即删除文件,请使用下面的方式
common io 包里面的
FileUtils.forceDelete(file);

或者是
final boolean delete = file.delete();

都可以立即删除对应的文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值