有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用“新建”Java文件API自动删除临时文件

在使用旧的FileAPI编写了多年之后,我终于准备好跳上整个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 the DELETE_ON_CLOSE option so that the file is deleted when the appropriate close method is invoked. Alternatively, a shutdown-hook, or the File.deleteOnExit() mechanism may be used to delete the file automatically.

我不知道应该在哪里指定DELETE_ON_CLOSE选项。使用关机挂钩非常不方便(除非我想错了)。为了避免同时使用Path对象File对象,我正在寻找一种类似于路径对象File.deleteOnExit()的解决方案,但显然不需要使用Path.toFile().[...].toPath()类调用模式

使用java.nio.FilesAPI实现“自毁”临时文件的正确方法是什么


共 (1) 个答案

  1. # 1 楼答案

    您可以在编写时设置该选项,例如:

    Path myTempFile = Files.createTempFile(...);
    Files.write(myTempFile, ..., StandardOpenOption.DELETE_ON_CLOSE);