Scala File I/O


Release date:2023-11-22 Update date:2023-11-22 Editor:admin View counts:126

Label:

Scala File I/O

Scala performs file writing operations, directly using the I/O class 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("Novice Tutorial")
      writer.close()
   }
}

Execute the above code and one will be produced in your current directory test.txt file, the content of which is “Rookie course”:

$ scalac Test.scala
$ scala Test
$ cat test.txt
Novice Tutorial

Read user input from the screen

Sometimes we need to receive instructions entered by the user on the screen to process the program. Examples are as follows:

Example

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

Post-Scala2.11 version Console.readLine abandoned, using scala.io.StdIn.readLine() method instead of.

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

$ scalac Test.scala
$ scala Test
Please enter the Rookie Tutorial official website : www.runoob.com
Thank you, what you entered is: www.runoob.com

Read content from a file

Reading from a file is very simple. We can use Scala’s Source class andaccompanying objects to read the file. The following example demonstrates reading from a “test.txt” (previously created) file:

Example

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

Execute the above code, and the output is as follows:

$ scalac Test.scala
$ scala Test
The file content is:
Novice Tutorial

Powered by TorCMS (https://github.com/bukun/TorCMS).