目录
摘要
逐行读取,读取到数组,读取到字符串,从 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") !