8.42. Scala File I/O

发布时间 : 2025-10-25 13:35:14 UTC      

Page Views: 9 views

Scala performs file writing operations, directly using the I/O class in java ( java.io.File ):

8.42.1. 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:

8.42.2. 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:

8.42.3. 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 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。