DELETE_ON_CLOSE deletes files before close on Linux

╄→尐↘猪︶ㄣ 提交于 2020-01-23 13:49:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18146637/delete-on-close-deletes-files-before-close-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!