Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting file being reopened in Java

I'm working on a small Java application (Java 1.6, Solaris) that will use multiple background threads to monitor a series of text files for output lines that match a particular regex pattern and then make use of those lines. I have one thread per file; they write the lines of interest into a queue and another background thread simply monitors the queue to collect all the lines of interest across the whole collection of files being monitored.

One problem I have is when one of the files I'm monitoring is reopened. Many of the applications that create the files I'm monitoring will simply restart their logfile when they are restarted; they don't append to what's already there.

I need my Java application to detect that the file has been reopened and restart following the file.

How can I best do this?

like image 548
Andrew Avatar asked Dec 09 '25 13:12

Andrew


2 Answers

Could you keep a record of each of the length of each file? When the current length subsequently goes back to zero or is smaller than the last time you recorded the length, you know the file has been restarted by the app?

like image 187
cagcowboy Avatar answered Dec 11 '25 02:12

cagcowboy


using a lockfile is a solution as Jurassic mentioned.

Another way is to try and open the file while you're reading the pattern and find if the file has a new size and create time. If the create time is NOT same as when you found it, then you can be sure that it has been recreated.

like image 37
anjanb Avatar answered Dec 11 '25 02:12

anjanb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!