Scala File I/O

Scala performs file write operations directly using the I/O classes in Java (java.io.File):

Example

import java.io._

object Test {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("Example")
      writer.close()
   }
}

After executing the above code, a test.txt file will be generated in your current directory, and the file content will be "Example":

$ scalac Test.scala 
$ scala Test
$ cat test.txt 
Example

Read user input from the screen

Sometimes we need to receive instructions entered by the user on the screen to process the program. An example is as follows:

Example

import scala.io._
object Test {
   def main(args: Array[String]) {
      print("Please enter the Example official website: " )
      val line = StdIn.readLine()

      println("Thank you, what you entered is: " + line)
   }
}

In versions after Scala 2.11Console.readLineit has been deprecated; usescala.io.StdIn.readLine()method instead.

After executing the above code, the following information will be displayed on the screen:

$ scalac Test.scala 
$ scala Test
请输入Example官网 : www.example.com
谢谢,你输入的是: www.example.com

Read content from a file

Reading content from a file is very simple. We can use Scala'sSourceclass and companion object to read files. The following example demonstrates reading content from the "test.txt" file (which was created earlier):

Example

import scala.io.Source

object Test {
   def main(args: Array[String]) {
      println("The file content is:" )

      Source.fromFile("test.txt" ).foreach{
         print
      }
   }
}

After executing the above code, the output result is:

$ scalac Test.scala 
$ scala Test
文件内容为:
Example
Other Extensions