scala:输入输出(I/O)
d:/test.txt文件内容:
1
2
1 2
程序:
import scala.io.Source
def main(args: Array[String]): Unit = {
val filename = "d:/test.txt"
var bufferedSource = Source.fromFile(filename)
//一行一个字符串,去掉行尾的换行符
bufferedSource.getLines.zipWithIndex.foreach{
case (line, idx) =>
println(idx + ":" + line)
}
bufferedSource.close
bufferedSource = Source.fromFile(filename)
//将文件返回一个完整字符串
println(bufferedSource.mkString)
bufferedSource.close
bufferedSource = Source.fromFile(filename)
println(bufferedSource.getLines.mkString("(", "|", ")")) //(1|2|1 2)
bufferedSource.close
bufferedSource = Source.fromFile(filename)
println(bufferedSource.getLines.toList) //List(1, 2, 1 2)
bufferedSource.close
}
输出:
0:1
1:2
2:1 2
1
2
1 2
(1|2|1 2)
List(1, 2, 1 2)