如何从文本文件创建 Akka Source[String]?

How do I create an Akka Source[String] from a text file?

这似乎是世界上最简单的事情,但我才刚刚开始,遇到了困难,所以请多多包涵。

FileIO 对象提供了 fromFile 函数,不出所料 returns 一个 Source[ByteString, Future[IOResult]].

但是我有一个 UTF 编码的文本文件,我想要一个 Source[String, Future[IOResult]] -- 也就是说,一个常规字符串的源,带有 unicode 字符,而不是无意义的字节串。

这是一个 Hello, World 级别的示例,但我卡住了。

(无济于事的是 scala.io.Sourceakka.stream.scaladsl.Source 之间的名称冲突,fromFile 正是我所需要的,所以如果有人可以向我解释一下,我'不胜感激。)

您可以使用 ByteString 中的 decodeString 函数解码为 UTF-x:

decodeString(charset: String): String

或者更常见的是,对于 UTF-8:

utf8String: String

所以,基本上:

val path = Paths.get("/tmp/example.txt")
FileIO.fromPath(path)
  .via(Framing.delimiter(ByteString(System.lineSeparator), maximumFrameLength=8192, allowTruncation=true))
  .map(_.utf8String)

请注意 FileIO.fromFile 现已弃用。

import akka.NotUsed

import scala.io.{Source => fileSource}
import akka.stream.scaladsl.{Source => strmSource}

val it = fileSource.fromFile("/home/expert/myfile.txt").getLines()
val source : strmSource[String, NotUsed] = strmSource.fromIterator(() => it)
  .map { line =>
    line.reverse
  }

这整个事情是延迟评估的,因此不会立即读取 100GB。