Easy Tutorial
❮ Scala Operators Scala If Else ❯

Scala File I/O

In Scala, file writing operations directly use Java's I/O classes (java.io.File):

Example

import java.io._

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

    writer.write("tutorialpro.org")
    writer.close()
  }
}

Executing the above code will create a file named "test.txt" in your current directory, with the content "tutorialpro.org":

$ scalac Test.scala
$ scala Test
$ cat test.txt
tutorialpro.org

Reading User Input from the Screen

Sometimes we need to accept user input from 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 tutorialpro.org official website: ")
    val line = StdIn.readLine()

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

>

In versions after Scala 2.11, Console.readLine has been deprecated, and the scala.io.StdIn.readLine() method is used instead.

Executing the above code will display the following information on the screen:

$ scalac Test.scala
$ scala Test
Please enter the tutorialpro.org official website: www.tutorialpro.org
Thank you, what you entered is: www.tutorialpro.org

Reading Content from a File

Reading content from a file is very simple. We can use Scala's Source class and its companion object to read files. The following example demonstrates reading content from the "test.txt" file (which has been created before):

Example

import scala.io.Source

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

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

Executing the above code, the output result will be:

$ scalac Test.scala
$ scala Test
The content of the file is:
tutorialpro.org
❮ Scala Operators Scala If Else ❯