File.createNewFile() thowing IOException No such file or directory

后端 未结 9 2458
感动是毒
感动是毒 2020-12-15 03:51

I have a method that writes to a log file. If the file exists it should append to it, if not then I want it to create a new file.

if (!file.exists() &&am         


        
9条回答
  •  -上瘾入骨i
    2020-12-15 04:15

    According to the [java docs](http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#createNewFile() ) createNewFile will create a new file atomically for you.

    Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

    Given that createNewFile is atomic and won't over-write an existing file you can re-write your code as

    try {
        if(!file.createNewFile()) {
            System.out.println("File already exists");
        } 
    } catch (IOException ex) {
        System.out.println(ex);
    }
    

    This may make any potential threading issues, race-conditions, etc, easier to spot.

提交回复
热议问题