title: Java - How to detect file deletion while writing to a file?
body: <p>Our java program writes some important data into a file continuously. Now we want to thrown some exception or display some kind of error message on the console whenever the file (to which the java program is writing) is deleted by some user manually.</p>
  
  <p>I found that java doesn't throw any exception when it tries to write to a file which has been deleted.</p>
  
  <p><strong>Method I -</strong> Start a new thread which will keep checking whether the file is there and notify the main java program about it when the file has been deleted. This won't work in our case as we will be having several files to which the java program will be writing so starting a new thread for every file will not be memory efficient.</p>
  
  <p><strong>Method II -</strong> Check for the existence of the file every time just before writing to the file. It is also not a good approach because checking the file existence is a costlier operation.</p>
  
  <p><strong>Method III -</strong> Extend <strong>java.io.FilterWriter</strong>(which we are using to write to a file) and override <strong>write()</strong> method to throw exception whenever it tries to write to a file that has been deleted. This seems to be a good solution but I couldn't find any place where Java is digesting some exception(when it tries to write to a file which has been deleted) which we can throw by overriding that method.</p>