在 Scala 中讀取整個檔案
Suraj P
2023年1月30日
Scala
Scala File

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