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

前端 未结 9 1926
我寻月下人不归
我寻月下人不归 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:47

    The ability to continue to read a file, and wait around until the file has some more updates for you shouldn't be that hard to accomplish in code yourself. Here's some pseudo-code:

    BufferedReader br = new BufferedReader(...);
    String line;
    while (keepReading) {
        line = reader.readLine();
        if (line == null) {
            //wait until there is more of the file for us to read
            Thread.sleep(1000);
        }
        else {
            //do something interesting with the line
        }
    }
    

    I would assume that you would want to put this type of functionality in its own Thread, so that you can sleep it and not affect any other areas of your application. You would want to expose keepReading in a setter so that your main class / other parts of the application can safely shut the thread down without any other headaches, simply by calling stopReading() or something similar.

提交回复
热议问题