English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala file I/O

Scala performs file writing operations directly using Java's I/O class (java.io.File) :

import java.io._
object Test {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt"))
      writer.write("Basic Tutorial Website")
      writer.close()
   }
}

Execute the above code, and a test.txt file will be created in your current directory, with the content as "Basic Tutorial Website":

$ scalac Test.scala 
$ scala Test
$ cat test.txt 
Basic Tutorial Website

Reading User Input from the Screen

Sometimes we need to receive instructions entered by the user on the screen to process the program. Here is an example:

import scala.io._
object Test {
   def main(args: Array[String]) {
      print("Please enter the official website of Basic Tutorial Website: ")
      val line = StdIn.readLine()
      println("Thank you, you entered: ") + line)
   }
}

Scala2.11 in later versions Console.readLine Deprecated, use the scala.io.StdIn.readLine() method instead.

Execute the above code, and the following information will be displayed on the screen:

$ scalac Test.scala 
$ scala Test
Please enter the official website of Basic Tutorial Website: www.oldtoolbag.com
Thank you, you entered: www.oldtoolbag.com

Reading content from a file

Reading content from a file is very simple. We can use Scala's Source This example demonstrates how to read the content from the "test.txt" file (which has been created previously):

import scala.io.Source
object Test {
   def main(args: Array[String]) {
      println("File Content:")
      Source.fromFile("test.txt").foreach{ 
         print 
      }
   }
}

Execute the above code, and the output result will be:

$ scalac Test.scala 
$ scala Test
File Content:
Basic Tutorial Website