Java IO implementation of unix/linux “tail -f”

前端 未结 9 1859
我寻月下人不归
我寻月下人不归 2020-11-22 12:06

I\'m wondering what techniques and/or library to use to implement the functionality of the linux command \"tail -f \". I\'m essentially looking for a drop in add-on/replace

9条回答
  •  情深已故
    2020-11-22 12:56

    Check JLogTailer, which does this logic.

    The main point in the code is:

    public void run() {
        try {
            while (_running) {
                Thread.sleep(_updateInterval);
                long len = _file.length();
                if (len < _filePointer) {
                    // Log must have been jibbled or deleted.
                    this.appendMessage("Log file was reset. Restarting logging from start of file.");
                    _filePointer = len;
                }
                else if (len > _filePointer) {
                    // File must have had something added to it!
                    RandomAccessFile raf = new RandomAccessFile(_file, "r");
                    raf.seek(_filePointer);
                    String line = null;
                    while ((line = raf.readLine()) != null) {
                        this.appendLine(line);
                    }
                    _filePointer = raf.getFilePointer();
                    raf.close();
                }
            }
        }
        catch (Exception e) {
            this.appendMessage("Fatal error reading log file, log tailing has stopped.");
        }
        // dispose();
    }
    

提交回复
热议问题