Monday 17 October 2016

File Tail implementation in Java

FileTail.java
import java.io.File;
import java.io.RandomAccessFile;

/**
 * Worker class to print the tail of a file. Use {@link FileTailUtil.getTail()}
 * method to get the tail of a file.
 * 
 */
public class FileTail implements Runnable {

 /**
  * Full Path of the file to watch
  */
 private String fileName;

 /**
  * Monitors the update of the file for every intervalTime seconds.
  */
 private int intervalTime = 2000;

 /**
  * Set the flag to true, to stop the execution of thread.
  */
 private volatile boolean stopThread = false;

 /**
  * File To watch
  */
 private File fileToWatch;

 /**
  * Variable used to get the last know position of the file
  */
 private long lastKnownPosition = 0;

 public FileTail(String fileName) {
  this(fileName, 2000);
 }

 public FileTail(String fileName, int intervalTime) {
  this.fileName = fileName;
  this.intervalTime = intervalTime;
  this.fileToWatch = new File(fileName);
 }

 @Override
 public void run() {

  if (!fileToWatch.exists()) {
   throw new IllegalArgumentException(fileName + " not exists");
  }
  try {
   while (!stopThread) {
    Thread.sleep(intervalTime);
    long fileLength = fileToWatch.length();

    /**
     * This case occur, when file is taken backup and new file
     * created with the same name.
     */
    if (fileLength < lastKnownPosition) {
     lastKnownPosition = 0;
    }
    if (fileLength > lastKnownPosition) {
     RandomAccessFile randomAccessFile = new RandomAccessFile(fileToWatch, "r");
     randomAccessFile.seek(lastKnownPosition);
     String line = null;
     while ((line = randomAccessFile.readLine()) != null) {
      System.out.println(line);
     }
     lastKnownPosition = randomAccessFile.getFilePointer();
     randomAccessFile.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   stopRunning();
  }

 }

 public boolean isStopThread() {
  return stopThread;
 }

 public void setStopThread(boolean stopThread) {
  this.stopThread = stopThread;
 }

 public void stopRunning() {
  stopThread = false;
 }

}

FileTailUtil.java
import java.io.File;

public class FileTailUtil {

 public static FileTail getTail(String fileToWatch) {
  if (fileToWatch == null || fileToWatch.isEmpty()) {
   throw new IllegalArgumentException("fileName shouldn't be empty");
  }

  /* Check for existence of file */
  File file = new File(fileToWatch);
  if (!file.exists()) {
   throw new IllegalArgumentException(fileToWatch + "doesn't exists");
  }

  FileTail fileTail = new FileTail(fileToWatch);
  Thread watcherThread = new Thread(fileTail);
  watcherThread.start();
  return fileTail;
 }
}

Main.java
public class Main {
 public static void main(String args[]) {
  if (args.length != 1) {
   System.out.println("usage: java Main fileName");
   return;
  }

  String fileToWatch = args[0];

  FileTail fileTail = FileTailUtil.getTail(fileToWatch);
 }
}




No comments:

Post a Comment