Im reading a log file in Java on a Linux box on a continual schedule of 2 minutes looking for certain messages. I store the last offset (RandomAccessFile getFilePointer) and read from it onwards when I detect LastModified has changed; is this best practice or even right?
Asked
Active
Viewed 1,052 times
2
-
Possible dupe of http://stackoverflow.com/questions/10118264/most-efficient-way-to-tail-poll-a-log-file-in-java – matt freake Jan 21 '13 at 11:13
-
Yip - but no real clarity on solution on approach. Lots of suggestions on third party tools and Java 7, but is the approach I use above correct if I implement it myself this way.... – Dane Balia Jan 21 '13 at 11:14
-
Good point - hopefully this thread will provide the clarity ! – matt freake Jan 21 '13 at 11:15
-
I don't know if I manage last file pointer, whether that will be right considering log rotations, file's trimmed or even deleted. I want to write the code myself and not add another layer with a third party. – Dane Balia Jan 21 '13 at 11:17
3 Answers
4
If you are using Java 7, then you can use WatchService to notify you when a File inside of a directory changes. This is similar to interrupts and doesn't need continuous polling. See this for more details on WatchService. Otherwise you are better off with the polling method you already do.

shazin
- 21,379
- 3
- 54
- 71
2
Try this Tailer: http://commons.apache.org/io/apidocs/org/apache/commons/io/input/Tailer.html
This is Java implementation of "tail -f" Unix functionality.

Max Golovanchuk
- 757
- 6
- 14
1
For detecting changes on files, or changes in any content inside directory, you can watch that directory for new content, modification of existing content and deletion of any existing content inside any directory.
See post: Directory watching for changes in java