Scala - 檔案 I/O



Scala 可以使用任何 Java 物件,並且java.io.File是可以在 Scala 程式設計中用於讀取和寫入檔案的一個物件。

以下是一個寫入檔案的示例程式。

示例

import java.io._

object Demo {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("test.txt" ))

      writer.write("Hello Scala")
      writer.close()
   }
}

將上述程式儲存在Demo.scala中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

它將在當前目錄(程式所在目錄)中建立一個名為Demo.txt的檔案。以下為此檔案的內容。

輸出

Hello Scala

從命令列讀取一行

有時您需要從螢幕讀取使用者輸入,然後進行進一步處理。以下示例程式向您展示瞭如何從命令列讀取輸入。

示例

object Demo {
   def main(args: Array[String]) {
      print("Please enter your input : " )
      val line = Console.readLine
      
      println("Thanks, you just typed: " + line)
   }
}

將上述程式儲存在Demo.scala中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

Please enter your input : Scala is great
Thanks, you just typed: Scala is great

讀取檔案內容

從檔案讀取非常簡單。您可以使用 Scala 的Source類及其伴生物件來讀取檔案。以下示例向您展示瞭如何從我們之前建立的"Demo.txt"檔案讀取。

示例

import scala.io.Source

object Demo {
   def main(args: Array[String]) {
      println("Following is the content read:" )

      Source.fromFile("Demo.txt" ).foreach { 
         print 
      }
   }
}

將上述程式儲存在Demo.scala中。以下命令用於編譯和執行此程式。

命令

\>scalac Demo.scala
\>scala Demo

輸出

Following is the content read:
Hello Scala
廣告