Java file open detection

I am working on a small Java application (Java 1.6, Solaris) that will use multiple background threads to control a series of text files for output strings that match a specific regular expression pattern and then use those strings. I have one stream per file; they write the lines of interest to the queue, and another background thread simply controls the queue to collect all the lines of interest in the entire collection of monitored files.

One of the problems that I encounter is when one of the files that I control opens again. Many of the applications that create files that I control simply restart their log file when they restart; they do not add to what is already there.

I need my Java application to detect that the file has been reopened and reloaded after the file.

How can i do this?

+3
source share
3 answers

Could you save a record of each length of each file? When the current length subsequently returns to zero or less than the last time you recorded the length, do you know that the file was restarted by the application?

+1
source

using a lock file is the solution mentioned in the Jurassic version.

Another way is to try to open the file while reading the template and find if the file has a new size and create time. If the creation time does not match the way you found it, you can be sure that it has been recreated.

+1
source

You can specify somewhere in the file system that indicates that you are reading the given file. Assume that next to the file being read (a.txt), you create a file next to it (a.txt.lock), which indicates that a.txt is being read. When your process is complete, a.txt.lock will be deleted. Each time the process proceeds to open the file for reading, it checks the lock file in advance. If the lock file is missing, it is not used. Hope this makes sense and answers your question. Hooray!

-1
source

Source: https://habr.com/ru/post/1697558/


All Articles