Monday, December 3, 2012

How to Implement tail -f in Java

package jtail;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class JTail {
    private static final long SLEEP_TIME = 500L;
    
    public static void open(File file) {
        RandomAccessFile raf = null;
        long lastFilePointer = 0;
        try {
            raf = new RandomAccessFile(file, "r");
            while (true) {
                if (raf.length() == lastFilePointer) {
                    // Don't forget to close the previous file handle
                    raf.close();
                    Thread.sleep(SLEEP_TIME);
                    // Wait till the file exists before opening it
                    while (!file.exists()) {}
                    raf = new RandomAccessFile(file, "r");
                    raf.seek(lastFilePointer);
                } else {
                    byte[] bytes = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = raf.read(bytes, 0, bytes.length)) != -1) {
                        System.out.print(new String(bytes, 0, bytesRead));
                    }
                    lastFilePointer = raf.getFilePointer();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    private static void printUsage() {
        System.out.println("Usage: java -cp <classpath> " +
            JTail.class.getName() + " <file>");
    }
    
    private static boolean validateArgs(String[] args) {
        if (args.length != 1) {
            printUsage();
            return false;
        }
        File file = new File(args[0]);
        if (!file.isFile()) {
            System.err.println("Error: " + file.getAbsolutePath() +
                " does not exist or is not a file");
            return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        if (!validateArgs(args)) {
            System.exit(1);
        }
        JTail.open(new File(args[0]));
    }
}

No comments:

Post a Comment