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.
I found that java doesn't throw any exception when it tries to write to a file which has been deleted.
Method I - 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.
Method II - 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.
Method III - Extend java.io.FilterWriter(which we are using to write to a file) and override write() 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.
Navigate to “Reports” → Click “File Servers” → Select “File Servers Activity” → Click “Files and Folders Deleted” → Click “View”.
files. deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is empty. Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.
delete() method deletes the file or directory defined by the abstract path name. To delete a directory, the directory must be empty.
The FileChannel and FileLock classes could be helpful in this case.
see How can I lock a file using java (if possible)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With