3

I have a program monitors log file changes. The program uses a FileInputStream to keep reading from the file. In the mean while, the log file might be rotated: the old log file is renamed and new log entries are written into a new file.

How can my program determines the file was rename so that it switch to read on the new log file?

aleung
  • 9,848
  • 3
  • 55
  • 69
  • 1
    Unless you're monitoring the file system for change events you really can't. What file system/platform are you developing for? – John Leidegren Apr 22 '11 at 09:04
  • will renaming succeed if the file is opened and actively read from? – Bozho Apr 22 '11 at 09:06
  • possible duplicate of [Is there a sophisticated file system monitor for Java which is freeware or open source?](http://stackoverflow.com/questions/1096404/is-there-a-sophisticated-file-system-monitor-for-java-which-is-freeware-or-open-s) – krock Apr 22 '11 at 09:22
  • Similar question with valuable answers: http://stackoverflow.com/questions/494869/file-changed-listener-in-java – aleung Dec 06 '13 at 10:16

3 Answers3

5

According to this question, JNotify sseems to be the perfect solution to your problem :

JNotify is a java library that allow java application to listen to file system events, such as:

File created

File modified

File renamed

File deleted

Community
  • 1
  • 1
Riduidel
  • 22,052
  • 14
  • 85
  • 185
0

Maybe you can watch the file system and make changes according to your needs.

npinti
  • 51,780
  • 5
  • 72
  • 96
  • 2
    Yes, but only if he's using Java 7. The `java.nio.file` package doesn't exist in Java 6 or earlier. – darioo Apr 22 '11 at 09:10
  • 1
    In fact there are backports for java.nio.file, like this question (http://stackoverflow.com/q/1096404/15619) answers mentions – Riduidel Apr 22 '11 at 09:17
0

The easiest way I can think of is simply to poll for the file size every 5 seconds or something like that.

If the file you are reading from was renamed and a new one was created, then your polling will show a sudden decrease in size. You can then recreate you FileinputStream accordingly.

Yahel
  • 8,522
  • 2
  • 24
  • 32
  • JNotify and java.nio.file sound good, but for my case polling for file size is more simple. – aleung May 10 '11 at 14:26
  • Finally we switched to JNotify. It's more reliable than polling for file size. If the old file was empty, file rotation can't be detected by comparing size. – aleung Dec 26 '11 at 04:12