import scala.io.{BufferedSource, Source}
object D02_按字符读取 {
def main(args: Array[String]): Unit = {
read1()
// read2()
}
def read1(): Unit = {
val source: BufferedSource = Source.fromFile("./data/2.txt")
// 以字符为单位读取
val iter: BufferedIterator[Char] = source.buffered
while (iter.hasNext) {
print(iter.next())
}
source.close()
}
def read2(): Unit = {
val source: BufferedSource = Source.fromFile("./data/2.txt")
// 若文件不大,则可以将其直接读取到一个字符串中
val str: String = source.mkString
println(str)
source.close()
}
}
2.txt内容
滕王阁序 【作者】王勃 【朝代】
滕王高阁临江渚,佩玉鸣鸾罢歌舞。
画栋朝飞南浦云,珠帘暮卷西山雨。
闲云潭影日悠悠,物换星移几度秋。
阁中帝子今何在?槛外长江空自流。
2.txt位置