Forum Stats

  • 3,727,836 Users
  • 2,245,474 Discussions
  • 7,853,058 Comments

Discussions

Consuming an increasing file with Java

User_4MPMN
User_4MPMN Member Posts: 5 Red Ribbon

Hi all,

I have to write a java program which have to parse an Apache log. As the Apache log grows continuously throughout the day I would like the java program listens continuously any new record in the log so I can parse it at real time. (I don't want to start to parse the log everytime from the beginning).

Any suggestions ?

Thanks in advance

Lele

Tagged:

Answers

  • Roland Mueller
    Roland Mueller Member Posts: 77 Blue Ribbon
    edited February 18

    Hello,

    here is some simple static method that behaves like Linux/Unix 'tail -f <some_filename>'.

    Sleep period is hardcoded to 3000ms and the payload i.e. what the method is doing with the file content is simply println() to stdout.

    BR,

    Roland

     12     public static void tail(String fname)
     13         throws InterruptedException, IOException, FileNotFoundException, InterruptedException
     14     {
     15         RandomAccessFile f = new RandomAccessFile( fname, "r" );
     16         long posInFile = 0;
     17 
     18         while (true) {
     19             long fileLength = f.length();
     20             if (fileLength > posInFile) {
     21                 f.seek(posInFile);
     22                 String line = f.readLine();
     23                 while( line != null ) {
     24                     System.out.println(line); // payload //
     25                     line = f.readLine();
     26                 }
     27                 posInFile = f.getFilePointer();
     28             }
     29 
     30             Thread.sleep(3000);
     31         }
     32     }
    


  • User_4MPMN
    User_4MPMN Member Posts: 5 Red Ribbon

    Hi Roland, thanks for your suggestion.

    I'll try it


    Gabriele

Sign In or Register to comment.