DELETE_ON_CLOSE在Linux上关闭之前删除文件 [英] DELETE_ON_CLOSE deletes files before close on Linux
问题描述
我使用Java 7 nio API获得以下代码:
I have this following code using Java 7 nio API:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class TestDeleteOnClose {
public static void main(String[] args) throws IOException {
Path tmp = Files.createTempFile("a", "b");
OutputStream out = Files.newOutputStream(tmp, StandardOpenOption.DELETE_ON_CLOSE);
ObjectOutputStream os = new ObjectOutputStream(out);
os.write(0);
os.flush();
System.out.println(Files.exists(tmp));
os.close();
System.out.println(Files.exists(tmp));
}
}
在Windows上,我看到了我的期望,即 true false
。在Linux上,我看到 false false
。这是预期的吗?难道我做错了什么?
文件被过早删除的事实是有问题的,因为我需要测试它的大小,例如在写入之后。
On Windows, I see what I expect, i.e true false
. On Linux I see false false
. Is it expected? Am I doing something wrong?
The fact that the file is deleted too early is problematic since I need to test it for its size for instance after having written to it.
我使用jdk7u25在Linux和Windows上都可以在具有RedHat或ArchLinux的机器上重现。
I use jdk7u25 on both Linux and Windows and could reproduce on machines with RedHat or ArchLinux on it.
编辑:即使我在另一次调用os.write()之前测试文件是否存在我被告知该文件不再存在。如果我使用 CREATE
选项打开文件,那么我将看到 true true
。
even if I test for file existence before another call to os.write() I am told the file does not exist anymore. If I open the file with the CREATE
options, then I will see true true
.
推荐答案
看起来Linux JVM会在您打开文件后立即删除该文件,这在Linux上可以实现。这也是我实现它的方式。您必须自己跟踪已经写入文件的数量,例如:插入一个计算字节数的 FilterOutputStream
。
It looks like the Linux JVM deletes the file as soon as you open it, which makes sense as you can do that on Linux. That's how I would implement it too. You'll have to keep track of how much has been written to the file yourself, e.g. by interposing a FilterOutputStream
that counts bytes.
这篇关于DELETE_ON_CLOSE在Linux上关闭之前删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!