File.createNewFile() randomly fails

前端 未结 3 775
谎友^
谎友^ 2021-01-25 14:06

I\'ve build a simple test which creates and deletes a file (name does not change) in an infinite loop. The test does run for a couple of seconds (sometimes over 77,000 iteration

3条回答
  •  萌比男神i
    2021-01-25 14:18

    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.

提交回复
热议问题