使用“新建”Java文件API自动删除临时文件
在使用旧的File
API编写了多年之后,我终于准备好跳上整个Path
/Paths
列车。在大多数情况下,这一切都进展顺利,然而,我在这个特殊的方面感到困惑:临时文件
关于^{
As with the
File.createTempFile
methods, this method is only part of a temporary-file facility. Where used as a work files, the resulting file may be opened using theDELETE_ON_CLOSE
option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or theFile.deleteOnExit()
mechanism may be used to delete the file automatically.
我不知道应该在哪里指定DELETE_ON_CLOSE
选项。使用关机挂钩非常不方便(除非我想错了)。为了避免同时使用Path
对象和File
对象,我正在寻找一种类似于路径对象File.deleteOnExit()
的解决方案,但显然不需要使用Path.toFile().[...].toPath()
类调用模式
使用java.nio.Files
API实现“自毁”临时文件的正确方法是什么
# 1 楼答案
您可以在编写时设置该选项,例如: