在 Scala 中读取整个文件

Suraj P 2023年1月30日 Scala Scala File
  1. 在 Scala 中方法 1:一次读取整个文件
  2. 在 Scala 中方法 2:逐行读取文件
在 Scala 中读取整个文件

Scala 提供了一个类来读取名为 Source 的文件。我们调用 Source 类的 fromFile() 方法来读取文件的内容,包括文件名作为参数来读取文件的内容。

在 Scala 中方法 1:一次读取整个文件

我们执行以下步骤在 Scala 中读取文件:

  • 首先,我们指定文件名及其完整路径。
  • 使用 Source.fromFile 创建文件将被加载的源。
  • 使用 mkstring 方法将整个数据变成一个字符串。
import scala.io.Source

object demo {
  def main(args:Array[String]): Unit =
  {
    val fileName= "C:\\Users\\user\\Desktop\\testFile.txt";
    val Str = Source.fromFile(fileName).mkString;  //using mkString method

    println(Str)
  }
}

输出:

[Chester Bennington:]
It's so unreal
[Mike Shinoda:]
It's so unreal, didn't look out below
Watch the time go right out the window
Trying to hold on but didn't even know
I wasted it all to watch you go

[Chester Bennington:]
Watch you go

Process finished with exit code 0

在 Scala 中方法 2:逐行读取文件

我们执行以下步骤在 Scala 中读取文件:

  • 首先,我们指定文件名及其完整路径。
  • 使用 Source.fromFile 创建文件将被加载的源。
  • 使用 getLines() 方法逐行读取数据,然后进行相应的打印或处理。
import scala.io.Source

object demo {
  def main(args:Array[String]): Unit =
  {
    val fileName= "C:\\Users\\user\\Desktop\\testFile.txt";  //filepath
    val fileSource = Source.fromFile(fileName)
    for(lines<-fileSource.getLines()) {
      println(lines)
    }
    fileSource.close();  //closing the file
  }
}

上面的代码读取了桌面文件夹中的 testFile.txt

输出:

"In The End"

[Chester Bennington:]
It starts with one
[Mike Shinoda:]
One thing I don't know why
It doesn't even matter how hard you try
Keep that in mind, I designed this rhyme
To explain in due time

[Chester Bennington:]
All I know
[Mike Shinoda:] Time is a valuable thing
Watch it fly by as the pendulum swings
Watch it count down to the end of the day
The clock ticks life away
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj P
Suraj P avatar Suraj P avatar

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.

LinkedIn GitHub

相关文章 - Scala File