在Groovy中尾随一个文件 [英] Tail a file in Groovy
问题描述
我想知道是否有一种简单的方式在Groovy中定位文件?我知道如何读取文件,但是如何读取文件,然后等待更多行添加,读取它们,等待等等。
I有什么我肯定是一个非常愚蠢的解决方案:
def lNum = 0
def num = 0
def numLines = 0
def myFile = new File(foo.txt)
def origNumLines = myFile.eachLine {num ++}
def precIndex = origNumLines
while(true){
num = 0
lNum = 0
numLines = myFile.eachLine {num ++}
if(numLines> origNumLines){
myFile.eachLine({line - >
if(lNum> precIndex){
println line
}
lNum ++
})
precIndex = numLines
Thread.sleep(5000)
}
请注意,我对调用Unixtail命令并不感兴趣。除非它是唯一的解决方案。
我写了一个类似于基本尾部功能的groovy类:
$ b
class TailReader {
boolean stop = false
public void stop(){
stop = true
}
public void tail(File file,Closure c){
def runnable = {
def reader
尝试{
reader = file.newReader()
reader.skip(file.length())
def line
while(!stop) {
line = reader.readLine()
if(line){
c.call(line)
}
else {
Thread.currentThread( ).sleep(1000)
}
}
}
finally {
reader。.close()
}
} as Runnable
def t = new Thread(runnable)
t.start()
}
}
tail
方法以文件和闭包作为参数。它将在一个单独的线程中运行,并会将每个新行添加到文件中以传递给给定的闭包。 tail
方法将一直运行,直到在 TailReader $ c上调用
stop
方法$ c>实例。下面是一个简单的例子,介绍如何使用 TailReader
类:
def reader = new TailReader()
reader.tail(new File(/ tmp / foo.log)){println it}
//执行其他操作,例如
// Thread.currentThread()。sleep(30 * 1000)
reader.stop()
I am wondering is there is a simple way to tail a file in Groovy? I know how to read a file, but how do I read a file and then wait for more lines to be added, read them, wait, etc...
I have what I am sure is a really stupid solution:
def lNum = 0
def num= 0
def numLines = 0
def myFile = new File("foo.txt")
def origNumLines = myFile.eachLine { num++ }
def precIndex = origNumLines
while (true) {
num = 0
lNum = 0
numLines = myFile.eachLine { num++ }
if (numLines > origNumLines) {
myFile.eachLine({ line ->
if (lNum > precIndex) {
println line
}
lNum++
})
}
precIndex = numLines
Thread.sleep(5000)
}
Note that I am not really interested in invoking the Unix "tail" command. Unless it is the only solution.
I wrote a groovy class which resembles the basic tail functionality:
class TailReader {
boolean stop = false
public void stop () {
stop = true
}
public void tail (File file, Closure c) {
def runnable = {
def reader
try {
reader = file.newReader()
reader.skip(file.length())
def line
while (!stop) {
line = reader.readLine()
if (line) {
c.call(line)
}
else {
Thread.currentThread().sleep(1000)
}
}
}
finally {
reader?.close()
}
} as Runnable
def t = new Thread(runnable)
t.start()
}
}
The tail
method taks a file and closure as parameters. It will run in a separate thread and will pass each new line that will be appended to the file to the given closure. The tail
method will run until the stop
method is called on the TailReader
instance. Here's a short example of how to use the TailReader
class:
def reader = new TailReader()
reader.tail(new File("/tmp/foo.log")) { println it }
// Do something else, e.g.
// Thread.currentThread().sleep(30 * 1000)
reader.stop()
这篇关于在Groovy中尾随一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!