Scala file I/O
Scala performs file writing operations directly using the I/O class in java (java.io.File):
import java.io._ object Test { def main(args: Array[String]) { val writer = new PrintWriter(new File("test.txt" )) writer.write("php中文网") writer.close() } }
Execute the above code, and it will Produce a test.txt file in your current directory. The content of the file is "php Chinese network":
$ scalac Test.scala $ scala Test $ cat test.txt php中文网
Read user input from the screen
Sometimes we need to receive The program handles the instructions entered by the user on the screen. The example is as follows:
object Test { def main(args: Array[String]) { print("请输入php中文网官网 : " ) val line = Console.readLine println("谢谢,你输入的是: " + line) } }
Execute the above code, the following information will be displayed on the screen:
$ scalac Test.scala $ scala Test 请输入php中文网官网 : www.php.cn 谢谢,你输入的是: www.php.cn
Reading content from the file
Reading the content from the file is very simple . We can use Scala's Source class and companion objects to read files. The following example demonstrates reading content from the "test.txt" (created before) file:
import scala.io.Source object Test { def main(args: Array[String]) { println("文件内容为:" ) Source.fromFile("test.txt" ).foreach{ print } } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test 文件内容为: php中文网