YouTip LogoYouTip

Scala File Io

# Scala File I/O For file write operations in Scala, the I/O classes from Java (**java.io.File**) are used directly: ## Example import java.io._ object Test { def main(args: Array){ val writer =new PrintWriter(new File("test.txt")) writer.write("") writer.close() } } Executing the above code will create a test.txt file in your current directory, with the file content as "": $ scalac Test.scala $ scala Test $ cat test.txt * * * ## Reading User Input from the Screen Sometimes we need to receive instructions input 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){ print("Please enter the official website. : ") val line = StdIn.readLine() println("Thank you, what you entered is.: " + line) } } > After Scala 2.11, **Console.readLine** is deprecated, use the scala.io.StdIn.readLine() method instead. Executing the above code will display the following information on the screen: $ scalac Test.scala $ scala TestPlease enter the official website. : www..com Thank you, what you entered is.: www..com * * * ## Reading Content from a File Reading content from a file is very simple. We can use Scala's **Source** class and companion object to read files. The following example demonstrates reading content from the "test.txt" file (created previously): ## Example import scala.io.Source object Test { def main(args: Array){ println("The file content is.:") Source.fromFile("test.txt").foreach{ print } } } Executing the above code, the output result is: $ scalac Test.scala $ scala TestThe file content is.:
← Css DimensionScala Extractors β†’