Step into Scala - 21 - I/O 操作与 Shell 操作

目录

摘要

逐行读取,读取到数组,读取到字符串,从 URL 读取,Shell 操作

I/O 操作与 Shell 操作

I/O 操作

读取操作
逐行读取
var source = Source.fromFile("coffeetime-scala/myfile.txt", "UTF-8")
val lineIterator = source.getLines()
for (l <- lineIterator) {
  println(l)
}
source.close()

source 使用完后要记得 close()

读取到数组中
val lines = source.getLines().toArray
读取到字符串中
val contents = source.mkString
逐字符读取
for (c <- source)
从控制台读取
val result = StdIn.readLine()
从 URL 中读取
val source1 = Source.fromURL("http://www.baidu.com")
从字符串中读取
val source2 = Source.fromString("hello world")
读取二进制文件

需要使用 Java 的方法

写入操作

需要使用 Java 的方法

序列化
@SerialVersionUID(42L)
class Book {
}

Shell 操作

前提

需要引入以下包

import sys.process._
执行代码
"ls -al .." !

以上!符号表示执行操作并输出到命令行,返回int 结果,0表示成功,1表示失败
如果将!换成!!表示返回 String 结果

将一个程序的结果通过管道输出到另一个程序
"ls -al .." #| "grep sec" !
将输出重定向到文件

覆盖

"ls -al .." #> new File("outputs.txt") !

追加

"ls -al .." #>> new File("outputs.txt") !
将内容作为输入

从文件

"grep sec" #< new File("outputs.txt") !

从 URL

"grep scala" #< new URL("http://www.baidu.com") !
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值