删除文件踩的坑

踩坑的点:

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

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.
 *
 * 

Once deletion has been requested, it is not possible to cancel the * request. This method should therefore be used with care. * *

* Note: this method should not 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 {@link * java.lang.SecurityManager#checkDelete} 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();

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

你可能感兴趣的:(今日所得,java)