在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有问题。就我个人而言,我在使用Source.fromFile打开大文件时遇到过问题,不得不求助于Java InputStreams。

另一个有趣的解决方案是使用scalax。下面是一些注释良好的代码示例,它使用ManagedResource打开日志文件,使用scalax helper打开文件:http://pastie.org/pastes/420714

其他回答

在scala.io.Source上使用getLines()会丢弃用于行结束符的字符(\n, \r, \r\n等)。

下面应该保持字符对字符,并且不会进行过多的字符串连接(性能问题):

def fileToString(file: File, encoding: String) = {
  val inStream = new FileInputStream(file)
  val outStream = new ByteArrayOutputStream
  try {
    var reading = true
    while ( reading ) {
      inStream.read() match {
        case -1 => reading = false
        case c => outStream.write(c)
      }
    }
    outStream.flush()
  }
  finally {
    inStream.close()
  }
  new String(outStream.toByteArray(), encoding)
}

打印每一行,就像使用Java BufferedReader读取每一行,然后打印它:

scala.io.Source.fromFile("test.txt" ).foreach{  print  }

相当于:

scala.io.Source.fromFile("test.txt" ).foreach( x => print(x))

为了扩展Daniel的解决方案,你可以通过在任何需要文件操作的文件中插入下面的导入来大大缩短时间:

import scala.io.Source._

有了这个,你现在可以做:

val lines = fromFile("file.txt").getLines

我会谨慎地将整个文件读入单个String。这是一个非常坏的习惯,它会比你想象的更快更严重地伤害你。getLines方法返回一个Iterator[String]类型的值。它实际上是文件中的惰性光标,允许您只检查所需的数据,而不会有内存过剩的风险。

哦,为了回答你隐含的关于Source的问题:是的,它是规范的I/O库。大多数代码最终都使用java。由于其较低级的接口和与现有框架的更好的兼容性,但是任何有选择的代码都应该使用Source,特别是对于简单的文件操作。

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

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
}

还有一个:https://github.com/pathikrit/better-files#streams-and-codecs

有多种方法可以在不将内容加载到内存的情况下获取文件:

val bytes  : Iterator[Byte]            = file.bytes
val chars  : Iterator[Char]            = file.chars
val lines  : Iterator[String]          = file.lines
val source : scala.io.BufferedSource   = file.content 

你也可以为任何执行读/写操作的东西提供你自己的编解码器(如果你没有提供,它会假设scala.io.Codec.default):

val content: String = file.contentAsString  // default codec
// custom codec:
import scala.io.Codec
file.contentAsString(Codec.ISO8859)
//or
import scala.io.Codec.string2codec
file.write("hello world")(codec = "US-ASCII")