首先我同意你的观点Files.write(myTempFile, ..., StandardOpenOption.DELETE_ON_CLOSE)
在此示例中,使用 DELETE_ON_CLOSE 是没有意义的。经过(不是那么激烈的)互联网搜索后,我能找到的唯一显示上述用法的示例就是您可能从中得到的示例(http://softwarecave.org/2014/02/05/create-temporary-files-and-directories-using-java-nio2/ http://softwarecave.org/2014/02/05/create-temporary-files-and-directories-using-java-nio2/).
该选项不适用于Files.write(...)
仅有的。这API https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#DELETE_ON_CLOSEmake 说得很清楚:
该选项主要用于与工作文件仅由 Java 虚拟机的单个实例使用。当打开由其他实体同时打开的文件时,不建议使用此选项。
抱歉,我无法给您提供一个有意义的简短示例,但请参阅操作系统使用的交换文件/分区等文件。如果当前的 JVM 需要在磁盘上临时存储数据,并且关闭后数据就不再有用。作为实际示例,我会提到它类似于 JEE 应用程序服务器,它可能决定将某些实体序列化到磁盘以释放内存。
edit也许可以用以下(过于简化的代码)为例来演示原理。 (所以请:没有人应该开始讨论这种“数据管理”可以以不同的方式完成,使用固定的临时文件名是不好的等等,......)
- 在 try-with-resource 块中,出于某种原因,您需要外部化数据(原因不是讨论的主题)
- 您可以随机读/写访问此外部化数据
- 此外部化数据仅在 try-with-resource 块内使用
- 使用 StandardOpenOption.DELETE_ON_CLOSE 选项,您不需要自己处理使用后的删除,JVM 会处理它(API 中描述了限制和边缘情况)
.
static final int RECORD_LENGTH = 20;
static final String RECORD_FORMAT = "%-" + RECORD_LENGTH + "s";
// add exception handling, left out only for the example
public static void main(String[] args) throws Exception {
EnumSet<StandardOpenOption> options = EnumSet.of(
StandardOpenOption.CREATE,
StandardOpenOption.WRITE,
StandardOpenOption.READ,
StandardOpenOption.DELETE_ON_CLOSE
);
Path file = Paths.get("/tmp/enternal_data.tmp");
try (SeekableByteChannel sbc = Files.newByteChannel(file, options)) {
// during your business processing the below two cases might happen
// several times in random order
// example of huge datastructure to externalize
String[] sampleData = {"some", "huge", "datastructure"};
for (int i = 0; i < sampleData.length; i++) {
byte[] buffer = String.format(RECORD_FORMAT, sampleData[i])
.getBytes();
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
sbc.position(i * RECORD_LENGTH);
sbc.write(byteBuffer);
}
// example of processing which need the externalized data
Random random = new Random();
byte[] buffer = new byte[RECORD_LENGTH];
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
for (int i = 0; i < 10; i++) {
sbc.position(RECORD_LENGTH * random.nextInt(sampleData.length));
sbc.read(byteBuffer);
byteBuffer.flip();
System.out.printf("loop: %d %s%n", i, new String(buffer));
}
}
}