Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 601929
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T16:46:04+00:00 2026-05-13T16:46:04+00:00

I’m trying to figure out how to continuously read a file and once there

  • 0

I’m trying to figure out how to continuously read a file and once there is a new line added, output the line. I’m doing this using a sleep thread however it just seems to blow through the whole file and exit the program.

Any suggestions what I’m doing wrong?

Here is my code:

import java.io.*;
import java.lang.*;
import java.util.*;

class jtail { 
    public static void main (String args[])
            throws InterruptedException, IOException{ 

        BufferedReader br = new BufferedReader(
                new FileReader("\\\\server01\\data\\CommissionPlanLog.txt"));

        String line = null;
        while (br.nextLine ) {
            line = br.readLine();
            if (line == null) {
                //wait until there is more of the file for us to read
                Thread.sleep(1000);
            }
            else {
                System.out.println(line);
            }
        }
    } //end main 
} //end class jtail 

thanks in advance

UPDATE: I’ve since changed the line “while (br.nextLine ) {” to just “while (TRUE) {“

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T16:46:05+00:00Added an answer on May 13, 2026 at 4:46 pm

    This in somewhat old, but I have used the mechanism and it works pretty well.

    edit: link no longer works, but I found it in the internet archive
    https://web.archive.org/web/20160510001134/http://www.informit.com/guides/content.aspx?g=java&seqNum=226

    The trick is to use a java.io.RandomAccessFile, and periodically check if the file length is greater that your current file position. If it is, then you read the data. When you hit the length, you wait. wash, rinse, repeat.

    I copied the code, just in case that new link stops working

    package com.javasrc.tuning.agent.logfile;
    
    import java.io.*;
    import java.util.*;
    
    /**
     * A log file tailer is designed to monitor a log file and send notifications
     * when new lines are added to the log file. This class has a notification
     * strategy similar to a SAX parser: implement the LogFileTailerListener interface,
     * create a LogFileTailer to tail your log file, add yourself as a listener, and
     * start the LogFileTailer. It is your job to interpret the results, build meaningful
     * sets of data, etc. This tailer simply fires notifications containing new log file lines, 
     * one at a time.
     */
    public class LogFileTailer extends Thread 
    {
      /**
       * How frequently to check for file changes; defaults to 5 seconds
       */
      private long sampleInterval = 5000;
    
      /**
       * The log file to tail
       */
      private File logfile;
    
      /**
       * Defines whether the log file tailer should include the entire contents
       * of the exising log file or tail from the end of the file when the tailer starts
       */
      private boolean startAtBeginning = false;
    
      /**
       * Is the tailer currently tailing?
       */
      private boolean tailing = false;
    
      /**
       * Set of listeners
       */
      private Set listeners = new HashSet();
    
      /**
       * Creates a new log file tailer that tails an existing file and checks the file for
       * updates every 5000ms
       */
      public LogFileTailer( File file )
      {
        this.logfile = file;
      }
    
      /**
       * Creates a new log file tailer
       * 
       * @param file         The file to tail
       * @param sampleInterval    How often to check for updates to the log file (default = 5000ms)
       * @param startAtBeginning   Should the tailer simply tail or should it process the entire
       *               file and continue tailing (true) or simply start tailing from the 
       *               end of the file
       */
      public LogFileTailer( File file, long sampleInterval, boolean startAtBeginning )
      {
        this.logfile = file;
        this.sampleInterval = sampleInterval;
      }
    
      public void addLogFileTailerListener( LogFileTailerListener l )
      {
        this.listeners.add( l );
      }
    
      public void removeLogFileTailerListener( LogFileTailerListener l )
      {
        this.listeners.remove( l );
      }
    
      protected void fireNewLogFileLine( String line )
      {
        for( Iterator i=this.listeners.iterator(); i.hasNext(); )
        {
          LogFileTailerListener l = ( LogFileTailerListener )i.next();
          l.newLogFileLine( line );
        }
      }
    
      public void stopTailing()
      {
        this.tailing = false;
      }
    
      public void run()
      {
        // The file pointer keeps track of where we are in the file
        long filePointer = 0;
    
        // Determine start point
        if( this.startAtBeginning )
        {
          filePointer = 0;
        }
        else
        {
          filePointer = this.logfile.length();
        }
    
        try
        {
          // Start tailing
          this.tailing = true;
          RandomAccessFile file = new RandomAccessFile( logfile, "r" );
          while( this.tailing )
          {
            try
            {  
              // Compare the length of the file to the file pointer
              long fileLength = this.logfile.length();
              if( fileLength < filePointer ) 
              {
                // Log file must have been rotated or deleted; 
                // reopen the file and reset the file pointer
                file = new RandomAccessFile( logfile, "r" );
                filePointer = 0;
              }
    
              if( fileLength > filePointer ) 
              {
                // There is data to read
                file.seek( filePointer );
                String line = file.readLine();
                while( line != null )
                {
                  this.fireNewLogFileLine( line );
                  line = file.readLine();
                }
                filePointer = file.getFilePointer();
              }
    
              // Sleep for the specified interval
              sleep( this.sampleInterval );
            }
            catch( Exception e )
            {
            }
          }
    
          // Close the file that we are tailing
          file.close();
        }
        catch( Exception e )
        {
          e.printStackTrace();
        }
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know there's a lot of other questions out there that deal with this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.