当前位置:网站首页>在 Scala 中读取整个文件
在 Scala 中读取整个文件
2022-07-30 12:20:00 【武念】
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
边栏推荐
猜你喜欢
随机推荐
Add the device library after Vivado installation
湖仓一体电商项目(一):项目背景和架构介绍
Tutorial on using the one-key upgrade function of the RTSP/Onvif video platform EasyNVR service
Matlab基础(1)——基础知识
数字化时代,寻求企业财务转型路径的最优解
私有化部署的即时通讯平台,为企业移动业务安全保驾护航
力扣——11.盛最多水的容器
PyQt5快速开发与实战 8.4 设置窗口背景 && 8.5 不规则窗口的显示
每天学一点Scala之 伴生类和伴生对象
SQL 根据时间范围查询数据
Mysql batch insert transaction unique key repeated processing
概率论的学习和整理--番外4: 关于各种平均数:算术平均数,几何平均数,调和平均数,以及加权平均数和平方平均数 (未完成)
Zhou Hongyi: Microsoft copied the 360 security model and became the largest security company in the United States
[PostgreSQL] - 存储结构及缓存shared_buffers
Unity Beginner 6 - Simple UI production (blood bar production) and audio addition and NPC dialogue bubbles (2d)
数据湖(十八):Flink与Iceberg整合SQL API操作
Matlab基础(4)——矩阵
Breaking the principle and introducing SQL, what does MongoDB want to do???
CMake library search function does not search LD_LIBRARY_PATH
【CVA估值训练营】如何快速读懂上市公司年报——第五讲