您如何用Java连续读取文件?

您如何用Java连续读取文件?,第1张

您如何用Java连续读取文件

这有点旧,但是我已经使用了该机制,并且效果很好。

编辑:链接不再有效,但我在Internet存档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.*;public class LogFileTailer extends Thread {    private long sampleInterval = 5000;    private File logfile;    private boolean startAtBeginning = false;    private boolean tailing = false;    private Set listeners = new HashSet();    public LogFileTailer( File file )  {    this.logfile = 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();    }  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5615872.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存