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

后端 未结 9 2484
感动是毒
感动是毒 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条回答
  •  醉话见心
    2020-12-15 04:06

    I think the exception you get is likely the result from the file check of the atomic method file.createNewFile(). The method can't check if the file does exist because some of the parent directories do not exist or you have no permissions to access them. I would suggest this:

    if (file.getParentFile() != null && !file.getParentFile().mkDirs()) {
        // handle permission problems here
    }
    // either no parent directories there or we have created missing directories
    if (file.createNewFile() || file.isFile()) {
        // ready to write your content
    } else {
        // handle directory here
    }
    

    If you take concurrency into account, all these checks are useless because in every case some other thread is able to create, delete or do anything else with your file. In this case you have to use file locks which I would not suggest doing ;)

提交回复
热议问题