目录

Scala - Files I/O

Scala是开放的,可以使用任何Java对象, java.io.File是可以在Scala编程中用于读写文件的对象之一。

以下是写入文件的示例程序。

例子 (Example)

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 。 以下命令用于编译和执行此程序。

Command

\>scalac Demo.scala
\>scala Demo

它将在当前目录中创建一个名为Demo.txt的文件,该文件放在该目录中。 以下是该文件的内容。

输出 (Output)

Hello Scala

从命令行读取一行

有时您需要从屏幕读取用户输入,然后继续进行进一步处理。 以下示例程序向您展示如何从命令行读取输入。

例子 (Example)

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

将上述程序保存在Demo.scala 。 以下命令用于编译和执行此程序。

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

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

阅读文件内容

从文件中读取非常简单。 您可以使用Scala的Source类及其伴随对象来读取文件。 以下是向您展示如何从我们之前创建的"Demo.txt"文件中读取的示例。

例子 (Example)

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 。 以下命令用于编译和执行此程序。

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

Following is the content read:
Hello Scala
↑回到顶部↑
WIKI教程 @2018