15

ファイルを継続的に読み取る方法を理解しようとしています。新しい行が追加されたら、その行を出力します。私はスリープスレッドを使用してこれを行っていますが、ファイル全体を吹き飛ばしてプログラムを終了しているようです。

私が間違っていることは何か提案はありますか?

これが私のコードです:

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 

前もって感謝します

更新: それ以来、「while (br.nextLine ) {」という行を「while (TRUE) {」だけに変更しました。

4

4 に答える 4

17

これはやや古いですが、私はメカニズムを使用しており、かなりうまく機能しています。

編集: リンクは機能しなくなりましたが、インターネット アーカイブで見つけました https://web.archive.org/web/20160510001134/http://www.informit.com/guides/content.aspx?g=java&seqNum=226

トリックは、を使用しjava.io.RandomAccessFile、ファイルの長さが現在のファイル位置よりも大きいかどうかを定期的に確認することです。そうであれば、データを読み取ります。長さを打ったら、待ってください。洗う、すすぐ、繰り返す。

新しいリンクが機能しなくなった場合に備えて、コードをコピーしました

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();
    }
  }
}
于 2010-02-05T23:59:32.877 に答える
6

複数のオブジェクトがファイルに来る新しい行の処理に関心を持つ可能性がある妥当なサイズのアプリケーションにこれを実装することを計画している場合は、Observerパターンを検討することをお勧めします。

ファイルから読み取るオブジェクトは、行が処理されるとすぐに、それにサブスクライブしている各オブジェクトに通知します。これにより、必要なクラスでロジックを適切に分離できます。

于 2010-02-06T00:27:24.123 に答える
3

これをゼロから作成する必要がない場合は、org.apache.commons.io.input.Tailerも検討してください。

于 2015-04-03T15:30:33.553 に答える
2

コードが現在書かれている方法では、ループに入る前に次の行があることを確認しているため、「line == null」のときにwhileループを通過しません。

代わりに、while(true){ }ループを実行してみてください。そうすれば、プログラムを終了させる条件に達するまで、常にループして一時停止のケースをキャッチします。

于 2010-02-05T22:51:45.017 に答える