读取行:

import scala.io.Source

object FileReader {
  def main(args: Array[String]): Unit = {
    val source = Source.fromFile("F:\\scalaWorkspace\\ScalaLearning\\files\\test.txt", "UTF-8")
    val lineIterator = source.getLines()
    for (line <- lineIterator) {
      println(line)
    }
//    lineIterator.toArray
    source.close()
    
    
    println("-------")
    val source1 = Source.fromFile("F:\\scalaWorkspace\\ScalaLearning\\files\\test.txt", "UTF-8")
    println(source1.mkString)
    source1.close()
  }
}

 

读取字符:

    val source2 = Source.fromFile("F:\\scalaWorkspace\\ScalaLearning\\files\\test.txt", "UTF-8")
    for (c <- source2){
      println(c)
    }
    source2.close()

如果想读取字符或行,但是不想处理掉,简单的说就是不希望游标下移,可以使用buffered。

//读取字符
    val source3 = Source.fromFile("F:\\scalaWorkspace\\ScalaLearning\\files\\test.txt", "UTF-8")
    val iter = source3.buffered
    while (iter.hasNext){
      println("head:" + iter.head)
      println("next:" + iter.next)
    }
    source3.close()

//读取行    
    val source4 = Source.fromFile("F:\\scalaWorkspace\\ScalaLearning\\files\\test.txt", "UTF-8")
    val lineIter = source4.getLines().buffered
    while(lineIter.hasNext){
      println("head:" + lineIter.head)
      println("next:" + lineIter.next)
    }
    source4.close()

控制台读取:

import scala.io.StdIn
 
println("How old are you")
val age = StdIn.readInt()
println(age)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
  • 2021-07-11
  • 2022-12-23
  • 2022-01-31
  • 2022-12-23
猜你喜欢
  • 2021-08-14
  • 2021-07-11
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-09-03
  • 2022-12-23
相关资源
相似解决方案