check file exists java

前端 未结 3 1918
Happy的楠姐
Happy的楠姐 2020-12-21 07:58

I want create text file but if the file already exists it should not create new file but should append the text to the content (at the end) of the existing file. How can I d

3条回答
  •  無奈伤痛
    2020-12-21 08:33

    do i have to check the condition if(file.exists){ }else{ new File(); }

    No you don't have to do that: see other answers for the solution.

    Actually, it would be a bad idea to do something like that, as it creates a potential race condition that might make your application occasionally die ... or clobber a file!

    Suppose that the operating system preempted your application immediately after the file.exists() call returns false, and gave control to some other application. Then suppose that the other application created the file. Now when your application is resumed by the operating system it will not realise that the file has been created, and try to create it itself. Depending on the circumstance, this might clobber the existing file, or it might cause this application to throw an IOException due to a file locking conflict.

    Incidentally, new File() does not actually cause any file system objects to be created. That only happens when you 'open' the file; e.g. by calling new FileOutputStream(file);

提交回复
热议问题