0

I want to know when a file has rotated because because I'm watching a file and I have to get a new file with the content of this file and the new file. I have to use Java6, so I don't have the new features of JDK7.

The problem is that when I rotate the file (keeping a reference to the file), the old reference gets updated, I would like that it'd point to the old file.

I was doing something like this:

  if (reader == null) {
    reader = new RandomAccessFile(toWatch, "r");
  }
  System.out.println("LasModified:" + new Date(toWatch.lastModified()));
  System.out.println("Cuando se creo to Watch long:" + reader.length());  --> lenght is okay.

 //Here, I use logrotate to simulate what it could happen. (I execute the code in debug mode to be able to do it            
 long len = 0L;        
 File f = new File("/home/gortiz/logRotate/test.flume");
 System.out.println("LasModified NewReader:" + new Date(f.lastModified()));

 RandomAccessFile newReader = new RandomAccessFile(toWatch, "r");
 len = reader.length(); --> len = 0
 long newLength = newReader.length(); --> newLenght = 0

I could check if there's a file with name.1. Usually logs system renames logs like that.. but, it's not a good solution because nobody guarantees that that's going to be as log system renames files or even they could be moved to another directory.

Guille
  • 2,248
  • 3
  • 24
  • 42
  • You may use [JNotify](http://jnotify.sourceforge.net/) with Java6. But I think you will get informed about deletion when the file is already gone ... – PeterMmm Feb 27 '14 at 08:38
  • If you are holding a reference to an open file, you can't lose it. The file can be renamed or deleted, but you can still read it. Always hold open the file you are reading and this won't happen. On Windows it will prevent the file being deleted, on Linux, it won't. – Peter Lawrey Feb 27 '14 at 08:38
  • what happen it's that the file rotates and the last reference points a file with 0 bytes. Anyway, I'm going to review the code again. – Guille Feb 27 '14 at 08:41
  • I'm going to check JNotify as well. – Guille Feb 27 '14 at 08:41
  • I have been going test, and when I rotate the file or I do something like cp file2 file1 to simnulate a rotate without logrotate it loses the reference as well. The only way it doesn't lose it, it's if I use mv file2 file1, It prints the old length and new one. I think if I'd use JNotify, I would have the same error.. – Guille Feb 27 '14 at 09:13

0 Answers0