天天看点

跟连乐一起学Scala-文件和正则表达式

文件和正则表达式

读取行

import scala.io.Source

val source = Source.fromFiles("myFile.txt", "UTF-8")
//第一个参数可以是字符串或者是java.io.File

val lineIterator = source.getLines
//得到的结果是一个迭代器

//处理
for(i <- lineIterator) //处理i

//处理成字符串:
val contents = source.mkString

//关闭
source.close()
           

读取字符

val source = Source.fromFile("myFile.txt", "UTF-8")
val iter = source.buffered
while (iter.hasNext) {
    if (iter.head是符合预期的) 
        //处理iter.next
    else 
        ...
}
source.close()
           

从URL或其他源读取

val source1 = Source.fromURL("http://www.baidu.com", "UTF-8")
val source2 = Source.fromString("Hello world!")
           

读取二进制文件

Scala中没有提供读取二进制文件的方法。你需要使用Java类库。
val file = new File(fileName)
val in = new FileInputStream(file)
val bytes = new Array[Byte](file.length.toInt)
in.read(bytes)
in.close()
           

写入文本文件

Scala中没有内建的对写入文件的支持。要写入文本文件,可使用java.io.PrintWriter
val out = new PrintWriter("text.txt")
for(i <-  to ) out.println(i)
out.close()
           

访问目录

import java.io.File

def subdirs(dir: File): Iterator[File] = {
    val children = dir.listFiles.filter(_.isDirectory)
    children.toIterator ++ children.toItrerator.flatMap(subdirs _)
}
           

序列化

@SerialVersionUID(L) class Person extends Serializable
//Serializable 特质定义在Scala包,因此不需要显式引入。
           
val fred = new Person(...)
import java.io._
val out = new ObjectOutputStream(new FileOutputStream("/home/lianle/tmp/test.obj"))
out.writeObject(fred)
out.close()
val in = new ObjectInputStream(new FileInputStream("/home/lianle/tmp/test.obj"))
val saveFred = in.readObject().asInstanceOf[Person]
           

进程控制

Scala可以和*nux中的shell很好的相处。
import sys.process._
"ls -al .." !  //显示上层目录的所有文件

val result = "ls -al .." !!  //将结果以字符串形式返回

"ls -al .." #| "grep sec" !  //将输出以管道形式传送到另一个程序

"ls -al .." #> new File("out.txt") !   //将输出重定向到文件

"ls -al .." #>> new File("out.txt") !   //将输出追加到文件

"grep sec" #< new File("out.txt") !  //将某个文件内容作为输入

"grep Scala" #< new URL("www.baidu.com") ! //从URL重定向输入
           

正则表达式

val numPattern = "[0-9]+".r

for(matchString <- numPattern.findAllIn("99 bottles, 98 bottles"))
//处理matchString
           

要检查是否某个字符串的开始部分能匹配,使用findPrefixOf:

numPattern.findPrefixOf("99 bottles, 98 bottles")
           

替换:

numPattern.replaceFirstIn("99 bottles, 98 bottles", "XX")

numPattern.replaceAllIn("99 bottles, 98 bottles", "XX")