Acceso Directo a un Fichero

El siguiente programa funciona de manera parecida a tail -f file.log el cual muestra las últimas líneas del fichero file.log actualizándolas conforme este crece.

generaciondecodigos@nereida:~/src/groovy/files$ cat -n tail.groovy  
 1  #!/usr/bin/env groovy                                         
 2  import java.lang.management.*                                 
 3                                                                
 4  if (args.length != 1) {                                       
 5    println "Usage:\n\ttail.groovy file"                        
 6    System.exit 1                                               
 7  }                                                             
 8                                                                
 9  // something like: 1466@machine                               
10  name = ManagementFactory.getRuntimeMXBean().getName();        
11  pid = Integer.parseInt(name[0..name.indexOf("@")-1])          
12  println "Stop with 'kill -9 $pid or CTRL-C'"                  
13                                                                
14  fileName = args[0]
15
16  if (!(fileName =~ /\.log$/)) fileName += '.log'
17
18  logfile = new File(fileName)
19
20  sampleInterval = 2000 // 2000 millis = 2 secs
21
22  // Create if it does not exists
23  logfile.createNewFile(); //  Atomically creates a new, empty file if a file with this name does not yet exist.
24
25  file = new RandomAccessFile( logfile, "r" )
26  filePointer = 0 // set to logfile.size() to begin tailing from the end of the file
27  while( true ) {
28      // Compare the length of the file to the file pointer
29      long fileLength = logfile.size()
30      if( fileLength < filePointer ) {
31          // Log file must have been rotated or deleted;
32          System.err.println "${new Date()}: Reopening $logfile"
33          logfile.createNewFile(); // create if deleted
34          file = new RandomAccessFile( logfile, "r" )
35          filePointer = 0
36      }
37      if( fileLength > filePointer ) {
38          // There is data to read
39          file.seek( filePointer )
40          while( (line = file.readLine()) != null ) {
41              println '##' + line
42          }
43          filePointer = file.filePointer
44      }
45      // Sleep for the specified interval
46      Thread.sleep( sampleInterval )
47  }

Al ejecutar el programa se queda esperando por cambios en el fichero vigilado:

$ rm my.log
$ ./tail.groovy my
Stop with 'kill -9 11542 or CTRL-C'
Tan pronto como en otra consola añadimos algo al fichero, queda reflejado en la salida del programa:
$ echo "Hola" >> my.log
$ echo "Mas Saludos" >> my.log
$ ./tail.groovy my
Stop with 'kill -9 11542 or CTRL-C'
##Hola
##Mas Saludos

Casiano Rodríguez León
2010-04-30