简体   繁体   English

Scala:将文件读取为无限/异步行流

[英]Scala: Read file as infinite/async stream of lines

I have a file /files/somelog.log that is continuously written to by some other process.我有一个文件/files/somelog.log由其他一些进程不断写入。 What I want to do is to read that file as a (never-ending) stream and respond to it whenever there is a new log line available.我想要做的是将该文件作为(永无止境的)流读取,并在有新的日志行可用时对其做出响应。

val logStream: Stream[String] = readAsStream("/files/somelog.log")
logStream.foreach { line: String => println(line) }

So, immediately when the other process writes anther line to the logfile, I expect the println above to go off (and keep going off).因此,当另一个进程将另一行写入日志文件时,我希望上面的println立即关闭(并继续关闭)。

However, that doesn't seem to be how the default Stream-type works.但是,这似乎不是默认 Stream 类型的工作方式。 Scala's Stream isn't async, it's just lazy. Scala 的 Stream 不是异步的,它只是懒惰。 What I'm probably looking for is something similar to what akka streams offers (I think).我可能正在寻找类似于 akka 流提供的东西(我认为)。 But Akka is so huge (150MB!) - I don't want to pull in so many new things that I don't need just to do something this simple/basic.但是 Akka 太大了(150MB!) - 我不想引入这么多新东西,我不需要做这么简单/基本的事情。 Is there really no other (tiny!) library or technique I can use?真的没有其他(微小的!)库或技术我可以使用吗?

If you simply want to tail the file you could use Tailer from Apache Commons IO:如果您只是想拖尾文件,您可以使用来自 Apache Commons IO 的Tailer

val l = new TailerListenerAdapter() {
    override def handle(line: String): Unit = println(line)
}

val tail = Tailer.create(new File("file.txt"), l)

I'm not actually recommending this, but you could roll your own.我实际上并不是推荐这个,但你可以自己动手。

def nextLine( itr: Iterator[String] ): String = {
  while (!itr.hasNext) Thread.sleep(2000)
  itr.next
}
. . .
val log = io.Source.fromFile("/files/somelog.log").getLines
val logTxt = nextLine( log )  // will block until next line is available
. . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM