我有一个包含 10 行的文件 - 我想检索它,然后用换行符 ("\n") 分隔符将它们拆分。
这就是我所做的
val data = io.Source.fromFile("file.txt").toString;
但是当我尝试在换行符上拆分文件时,这会导致错误。
然后我尝试了
val data = io.Source.fromFile("file.txt").mkString;
它奏效了。
什么鬼?谁能告诉我这两种方法有什么区别?
最佳答案
让我们看看类型,好吗?
scala> import scala.io._
import scala.io._
scala> val foo = Source.fromFile("foo.txt")
foo: scala.io.BufferedSource = non-empty iterator
scala>
现在,您已将文件 foo.txt
读入的变量是一个迭代器。如果您对其执行 toString()
调用,它不会返回文件的 contents,而是您创建的迭代器的字符串表示形式。 OTOH,mkString()
读取迭代器(即对其进行迭代)并根据从中读取的值构造一个长字符串。
有关更多信息,请查看此控制台 session :
scala> foo.toString
res4: java.lang.String = non-empty iterator
scala> res4.foreach(print)
non-empty iterator
scala> foo.mkString
res6: String =
"foo
bar
baz
quux
dooo
"
scala>
关于java - scala中的toString和mkString有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9747255/