Java‎ > ‎

File Monitoring with TailInputStream

TailInputStream is Java class that behaves like Unix/Linux command tail -f. Using this class it is possible to read data at the end of a file as the file grows, i.e. it can be used to monitor the end of a file that is being written by other data producers. Using TailInputStream the file can be closed and reopened multiple times by data producers that write data at the end of the file that is monitored.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
 
public class TailInputStream extends InputStream {
  File file;
  InputStream in;
 
  public TailInputStream(File file) throws FileNotFoundException {
    super();
    in = new FileInputStream(file);
  }
 
  @Override
  public int available() throws IOException {
    return in.available();
  }
 
  public int read() throws IOException {
    int readByte = -1;
    do {
      if (in.available() > 0) {
        if ((readByte = in.read()) != -1) {
          break;
        }
      }
      try {
        Thread.sleep(9);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    } while (readByte == -1);
 
    return readByte;
  }
 
  public int read(byte b[], int off, int len) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    } else if (off < 0 || len < 0 || len > b.length - off) {
      throw new IndexOutOfBoundsException();
    } else if (len == 0) {
      return 0;
    }
 
    int c = read();
    if (c == -1) {
      return -1;
    }
    b[off] = (byte) c;
 
    return 1;
  }
 
  public void close() throws IOException {
    in.close();
  }
}

Class TailInputStream can be used as shown in next example.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Program {
  public static void main(String[] args) throws IOException {
    TailInputStream tailIn = new TailInputStream(new File("c:\\test.txt"));
    InputStreamReader readerIn = new InputStreamReader(tailIn);
    BufferedReader in = new BufferedReader(readerIn);
 
    String line = null;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
  }
}

Comments