Scala文件操作

Zhengpeng Liao Lv3

文件操作

主要利用scala和java提供的标准库。

读文件:

1
2
3
4
5
6
import scala.io.Source
val f = Source.fromFile("a.txt")
f.getLines().foreach{ line=>
println(line)
}//打印每一行
f.close()

写文件:

1
2
3
4
5
6
import java.io.{File, PrintWriter}
val writer = new PrintWriter(new File("a.txt"))
for(i <- 0 to 10) {
writer.println(s"index: $i")
}//写入文件每行"index: 1\nindex: 2..."
writer.close()//一定要记得关闭文件
  • 标题: Scala文件操作
  • 作者: Zhengpeng Liao
  • 创建于 : 2022-03-04 16:35:24
  • 更新于 : 2026-10-24 17:55:32
  • 链接: https://wswslzp.github.io/2022/03/04/Scala文件操作/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
目录
Scala文件操作