File.createNewFile() randomly fails

老子叫甜甜 提交于 2019-12-02 06:32:05

I've found an explanation while writing the question. I still posted the question because I wanted to share what I learned.

My application is not the only process on the system accessing files. The Windows Search Index Service for example could open this file because it wants to add it to it's index. Or the windows Explorer if it is updating the view.

Try this:

final File f = new File("file");
    while (true) {
        final boolean create = f.createNewFile();
        if (!create) {
            System.out.println("crate failed");
        } else {
            final boolean delete = f.delete();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                System.out.println("...");
            }
            if (!delete) {
                System.out.println("delete failed");
            }
        }
    }

In this way we ensure that the file is released by the delete before invoking createNewFile.

This issue reminds me a problem I experienced recently with the File.renameTo() method. It is (was?) due to this bug in the jvm :

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298

A weird workaround is to call System.gc() and to retry renaming the file again (and it works...).

Not sure it has a link with your issue, but it may be worth exploring...

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