Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to detect file deletion while writing to a file?

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.

like image 862
Yatendra Avatar asked Jun 23 '11 07:06

Yatendra


People also ask

How do you check if a file is deleted?

Navigate to “Reports” → Click “File Servers” → Select “File Servers Activity” → Click “Files and Folders Deleted” → Click “View”.

How do you check if a file exists in Java and delete it?

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.

What does delete file do Java?

delete() method deletes the file or directory defined by the abstract path name. To delete a directory, the directory must be empty.


1 Answers

The FileChannel and FileLock classes could be helpful in this case.

see How can I lock a file using java (if possible)

like image 110
splash Avatar answered Nov 15 '22 14:11

splash