你如何不断阅读Java中的文件? [英] How do you continuously read a file in Java?

查看:176
本文介绍了你如何不断阅读Java中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何连续读取一个文件,并且一旦添加了一个新行,就输出该行。我正在做这个使用睡眠线程,但它似乎只是吹了整个文件,并退出程序。



有什么建议我做错了?



以下是我的代码:

  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(\\\\\\\\\\\\\\\\\\));

String line = null;
while(br.nextLine){
line = br.readLine();
if(line == null){
//等到有更多的文件供我们读取
Thread.sleep(1000);
}
else {
System.out.println(line);
}

} // end main
} // end class jtail

在此先感谢

更新:我改变了行while(br.nextLine){to justwhile(TRUE ){

解决方案

这个有点旧,但是我用过这个机制,效果很好。 b
$ b

编辑:链接不再有效,但我在互联网存档中找到它
https://web.archive.org/web/20160510001134/http://www.informit .com / guides / content.aspx?g = java& seqNum = 226
$ b

诀窍是使用 java.io .RandomAccessFile ,并定期检查文件长度是否大于当前文件位置。如果是这样,那么你读的数据。当你打的时候,你等一下。

我复制了代码,以防万一新链接停止工作

  package com.javasrc.tuning.agent.logfile; 

import java.io. *;
import java.util。*;
$ b $ / **
*日志文件定位器用于监视日志文件,并在将新行添加到日志文件时发送通知
*。这个类有一个类似于SAX解析器的通知
*策略:实现LogFileTailerListener接口,
*创建一个LogFileTailer来记录日志文件,添加自己作为一个监听器,
*启动LogFileTailer。这是你的工作来解释结果,建立有意义的
*数据集等。这个tailer只是一次触发包含新的日志文件行
*的通知。
* /
public class LogFileTailer extends Thread
{
/ **
*检查文件更改的频率;默认为5秒
* /
private long sampleInterval = 5000;

/ **
*日志文件尾部
* /
私有文件日志文件;
$ b $ **
*定义日志文件尾部是否应该包含尾部启动时尾部文件尾部的尾部文件尾部的全部内容
* b $ b * /
private boolean startAtBeginning = false;

/ **
*零售商目前是否拖尾?
* /
private boolean tailing = false;
$ b / **
*侦听器集合
* /
private设置侦听器= new HashSet();
$ b $ / **
*创建一个新的日志文件tailer尾巴现有的文件,并检查文件$ ​​b $ b *每5000毫秒更新
* /
公共LogFileTailer(文件文件)
{
this.logfile = file;

$ b / **
*创建一个新的日志文件tailer
*
* @param文件尾部
* param sampleInterval检查日志文件更新的频率(默认= 5000ms)
* @param startAtBeginning如果tailer只是简单的拖尾,或者应该处理整个
*文件并继续拖尾(true)或者干脆开始从文件的
*结尾开始加尾
* /
public LogFileTailer(File sample,long sampleInterval,boolean startAtBeginning)
{
this.logfile = file;
this.sampleInterval = sampleInterval;

$ b $ public void addLogFileTailerListener(LogFileTailerListener l)
{
this.listeners.add(l);

$ b $ public void removeLogFileTailerListener(LogFileTailerListener l)
{
this.listeners.remove(l);

$ b $保护无效fireNewLogFileLine(字符串行)
{
for(Iterator i = this.listeners.iterator(); i.hasNext();)
{
LogFileTailerListener l =(LogFileTailerListener)i.next();
l.newLogFileLine(line);


$ b $ public void stopTailing()
{
this.tailing = false;

$ b $ public void run()
{
//文件指针跟踪我们在文件中的位置
long filePointer = 0;

//确定起点
if(this.startAtBeginning)
{
filePointer = 0;
}
else
{
filePointer = this.logfile.length();
}

尝试
{
//开始拖尾
this.tailing = true;
RandomAccessFile file = new RandomAccessFile(logfile,r);
while(this.tailing)
{
try
{
//比较文件长度与文件指针
long fileLength = this。 logfile.length();
if(fileLength {
//日志文件必须已被旋转或删除;
//重新打开文件并重置文件指针
file = new RandomAccessFile(logfile,r);
filePointer = 0;

$ b $ if(fileLength> filePointer)
{
//有数据读取
file.seek(filePointer);
String line = file.readLine();
while(line!= null)
{
this.fireNewLogFileLine(line);
line = file.readLine();
}
filePointer = file.getFilePointer();


//在指定的时间间隔休眠
sleep(this.sampleInterval);

catch(Exception e)
{
}
}

//关闭我们拖曳的文件
file.close();

catch(Exception e)
{
e.printStackTrace();
}
}
}


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) {"

解决方案

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();
    }
  }
}

这篇关于你如何不断阅读Java中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆