在java中轮询文件,将最新的写入文件内容添加到字符串中

时间:2016-05-19 11:58:56

标签: java file io polling

我想创建一个无限轮询日志文件的java程序。每当有一些条目进入该日志文件时,我想将最新内容读入刚写入的文件中。

任何人都可以告诉我这样做的有效方法吗?因为这应该24/7运行获得CPU峰值是不可取的。

我做了我的基础研究,发现了以下但没有多大帮助: https://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes

1 个答案:

答案 0 :(得分:1)

一种非常简单有效的方法是使用WatchService。 这是一个代码示例,它在文件创建,修改,删除时引发事件。

public void onDraw(Canvas canvas){
    Path path = new Path();
    for(String eachLine: text){
        path.moveTo(startX,startY);
        path.lineTo(endX,endY);
        canvas.drawTextOnPath(eachLine,path,0,0,painter);
        ...
    }
    ....
//the startX,startY,endX, endY has already took the padding into consideration.
//*NOTE: The only solution that I can think of is that I control this 
//drawing logic according to the padding. But this approach still won't fix the 
//problem, for example: what if I scroll half line height? How do I draw the 
//half of the line? So there must be some other approach that I don't know.
}