2

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));
    }
}

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.

I use jdk7u25 on both Linux and Windows and could reproduce on machines with RedHat or ArchLinux on it.

EDIT: 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.

4

1 回答 1

6

看起来 Linux JVM 一打开文件就会删除它,这很有意义,因为您可以在 Linux 上执行此操作。这也是我将如何实现它的方式。您必须自己跟踪已写入文件的数量,例如通过插入FilterOutputStream计算字节数的 a 。

于 2013-08-11T23:13:33.680 回答