在Scala中,将整个文件读入内存的简单而规范的方法是什么?(理想情况下,可以控制字符编码。)

我能想到的最好的是:

scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_)

或者我应该使用Java的一个可怕的习语,其中最好的(不使用外部库)似乎是:

import java.util.Scanner
import java.io.File
new Scanner(new File("file.txt")).useDelimiter("\\Z").next()

通过阅读邮件列表讨论,我甚至不清楚scala.io.Source是否应该是规范的I/O库。我不明白它的目的到底是什么。

... 我想要一些简单易记的东西。例如,在这些语言中,很难忘记成语……

Ruby    open("file.txt").read
Ruby    File.read("file.txt")
Python  open("file.txt").read()

当前回答

您不需要解析每一行,然后再次将它们连接起来。

Source.fromFile(path)(Codec.UTF8).mkString

我更喜欢用这个:

import scala.io.{BufferedSource, Codec, Source}
import scala.util.Try

def readFileUtf8(path: String): Try[String] = Try {
  val source: BufferedSource = Source.fromFile(path)(Codec.UTF8)
  val content = source.mkString
  source.close()
  content
}

其他回答

你可以使用

Source.fromFile(fileName).getLines().mkString

但是应该注意的是,getLines()删除了所有新的行字符。 如果你想保存格式,你应该使用

Source.fromFile(fileName).iter.mkString

Java 8 +

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

val path = Paths.get("file.txt")
new String(Files.readAllBytes(path), StandardCharsets.UTF_8)

Java 11 +

import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Path}

val path = Path.of("file.txt")
Files.readString(path, StandardCharsets.UTF_8)

它们提供了对字符编码的控制,并且不需要清理资源。由于更高效的分配模式,它也比其他模式(例如getLines(). mkstring ("\n"))更快。

正如一些人提到的,scala.io.Source最好避免使用,因为它会导致连接泄漏。

也许scalax和像commons-io这样的纯java库是最好的选择,直到新的孵化器项目(即scala-io)被合并。

您不需要解析每一行,然后再次将它们连接起来。

Source.fromFile(path)(Codec.UTF8).mkString

我更喜欢用这个:

import scala.io.{BufferedSource, Codec, Source}
import scala.util.Try

def readFileUtf8(path: String): Try[String] = Try {
  val source: BufferedSource = Source.fromFile(path)(Codec.UTF8)
  val content = source.mkString
  source.close()
  content
}
// for file with utf-8 encoding
val lines = scala.io.Source.fromFile("file.txt", "utf-8").getLines.mkString