Scala file I / O
Scala for file write operations are java directly in the I / O type(java.io.File):
import java.io._ object Test { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt" )) writer.write("本教程") writer.close() } }
Execute the above code will produce a test.txt file in your current directory, file contents as the "Guide":
$ scalac Test.scala $ scala Test $ cat test.txt 本教程
Read user input from the screen
Sometimes we need to receive user input to the instruction screen handler. Examples are as follows:
object Test { def main(args: Array[String]) { print("请输入本教程官网 : " ) val line = Console.readLine println("谢谢,你输入的是: " + line) } }
Execute the above code will display the following message on the screen:
$ scalac Test.scala $ scala Test 请输入本教程官网 : www.w3write.com 谢谢,你输入的是: www.w3write.com
Read from the file
Read the contents from the file is very simple. We can use Scala'sSource and associated class object to read the file.The following example demonstrates the "test.txt" (previously have been created) reads the contents of the file:
import scala.io.Source object Test { def main(args: Array[String]) { println("文件内容为:" ) Source.fromFile("test.txt" ).foreach{ print } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 文件内容为: 本教程