When is it okay to check if a file exists?

前端 未结 18 2383
再見小時候
再見小時候 2020-11-28 06:52

File systems are volatile. This means that you can\'t trust the result of one operation to still be valid for the next one, even if it\'s the next line of code. You can\'t

18条回答
  •  一向
    一向 (楼主)
    2020-11-28 07:19

    To answer my own question (in part), I want to expand on the example I used: a default config file.

    Rather than check if it exists at app startup and try to copy the file if the check fails, the thing to do is always try to copy the file. You just do it in such a way that the copy will fail if the file exists rather than replace an existing file. This way all you need to do is catch and ignore any exception thrown if the copy fails because of an existing file.

提交回复
热议问题