Scala read file
程序员文章站
2022-04-19 17:17:00
...
// use loan pattern
// close resource after used
def using[A <: { def close(): Unit}, B]
(resource: A)(f: A => B): B = {
try {
f(resource)
} finally {
resource.close()
}
}
// use Option as return
def readTextFile(filename: String): Option[List[String]] = {
try {
val lines = using(Source.fromFile(filename)) {
source =>
source.getLines.toList
}
Some(lines)
} catch {
case e: Exception => None
}
}
// print lines
val lines = readTextFile(filename).get
lines.foreach { line =>
println(line)
}
转载于:https://www.jianshu.com/p/bc99e758654f
上一篇: golang *FILE Read方法
推荐阅读
-
Mysql启动中 InnoDB: Error: log file ./ib_logfile0 is of different size 0 5242880 bytes 的问题
-
Android 中Failed to read key from keystore解决办法
-
HTML5 File接口在web页面上使用文件下载
-
Starting MySQL.Manager of pid-file quit without updating file.[FAILED]的解决方法
-
mysql启动报错MySQL server PID file could not be found
-
JDK1.7 之java.nio.file.Files 读取文件仅需一行代码实现
-
利用html5 file api读取本地文件示例(如图片、PDF等)
-
HTML5 File API改善网页上传功能
-
记录无法安装mysql-Invalid GPG Key from file:/etc/pki/rpm-gpg/RPM-GPG-KEY-mysql的解决办法
-
详解auto-vue-file:一个自动创建vue组件的包