当前位置:网站首页>在 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
边栏推荐
- Matlab基础(1)——基础知识
- Zhou Hongyi: Microsoft copied the 360 security model and became the largest security company in the United States
- MySQL【多表查询】
- Win11打不开exe应用程序怎么办?Win11无法打开exe程序解决方法
- Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered
- 崩了,该来的终究躲不掉
- CMake库搜索函数居然不搜索LD_LIBRARY_PATH
- 基于柔性人机接口的人机协调运动控制方法
- 北上广线下活动丨年底最不可错过的技术聚会都齐了
- IO/multiplexing (select/poll/epoll)
猜你喜欢

ECCV 2022 | 新加坡国立大学提出:全新可恢复型模型遗忘框架LIRF!

双击Idea图标打不开——解决办法

【语音识别】基于GMM-HMM的语音识别系统

概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!

什么是驱动程序签名,驱动程序如何获取数字签名?

CV-Model【2】:MobileNet v1

Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered

最基础01/完全背包

使用百度EasyDL实现明厨亮灶厨师帽识别

重建丢失的数据
随机推荐
Kubernetes之本地存储
力扣——11.盛最多水的容器
【MySQL系列】-B+树索引和HASH索引有什么区别
JS事件参数对象event
saltstack学习2grains&pillar
Mysql batch insert transaction unique key repeated processing
基于DoS攻击能量分级的ICPS综合安全控制与通信协同设计
IO/multiplexing (select/poll/epoll)
[SCTF2019]Flag Shop
[PostgreSQL] - explain SQL分析介绍
北上广线下活动丨年底最不可错过的技术聚会都齐了
saltstack学习1入门基础
每天学一点Scala之 伴生类和伴生对象
dolphinscheduler单机化改造
AlphaFold预测了几乎所有已知蛋白质!涵盖100万物种2.14亿结构,数据集开放免费用...
干货分享:小技巧大用处之Bean管理类工厂多种实现方式
PanGu-Coder: 函数级的代码生成模型
崩了,该来的终究躲不掉
13-GuliMall Basics Summary
[BJDCTF2020]Cookie is so stable-1|SSTI injection