1. 读取行
读取文件中的所有行: 调用scala.ios.Source对象的getLines方法:
结果是一个迭代器。对结果进行处理:import scala.ios.Source var source=Source.fromFile("myfile.txt","utf-8") //第一个参数可以是字符串或者java.io.File //第二个字符编码可以省略 val lineIterator =source.getLines
1)可以逐条处理这些行
for (x<-lineIterator) 处理 x
2)存放数组或者缓冲
或者使用toArray 或 toBuffer方法,将行存放到数组或者缓冲中:
val lines =source.getLines.toArray
3)读取字符串
将整个文件读取成一个字符串
注意: 使用完source对象后,要调用closeval contents=source.mkString
2. 读取字符
从文件中读取单个字符,可以将Source对象当做迭代器进行处理:
查看某个字符但不处理掉,调用source对象的buffered 方法。可以用head方法查看下一个字符,但同时并不把它当做是已处理的字符for (c <-source) 处理c
若文件不是很大,可以读取成字符串进行处理val source=Source.fromFile("myfile.txt","utf-8") val iter=source.buffered while(iter.hasNext){ if(iter.head是符合预期的) 处理iter.next else ... } source.close
val contents=source.mkString
3. 读取词法单元和数字
1)读取源文件中所有以空格隔开的词法单元
val tokens =source.mkString.split("\\S+")
2)字符串转换成数字
使用toInt或toDouble方法
提示: 可以使用java.util.Scanner类处理同时包含文本和数字的文件val numbers=for( w <-tokens) yield w.toDouble val numbers =tokens.map(_.toDouble)
3) 从控制台读取数字
print("how are you?") val age=readInt()//或者readDouble 或者readLong
4. 从URL或者其他源读取
val source1=Source.fromURL("http://horstamnn.com","utf-8") val source2=Source.formString("hello") val source3=Source.stdin //从标准输入读取
5. 读取二进制文件
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()
6. 写入文本文件
scala没有内建的对写入文件的支持,可以使用java.io.PrintWriter
val out=new PrintWriter("numbers.txt") for( i<-1 to 100) out.println(i) out.close()
7. 序列化
说明:如果你能接受缺省ID,可以省略@SerialVersionUID注释@SerialVersionUID(42L) class Person extends Serializable
8.正则表达式
scala.util.matching.Regex类来处理正则表达式,需要构造一个Regex对象,使用String类的r方法即可:若正则表达式中包含反斜杠或者引号,最好使用“原始”字符串语法"""..."""。val numPattern ="[0-9]+".r
findAllIn方法返回遍历所有匹配项的迭代器。可以在for循环中使用:val pattern="""\s+[0-9]+\s+""".r
或者将迭代器转成数组for( ms<-numPattern.findAllIn("99 bottles")) 处理ms
val matches=numPattern.findAllIn("99 bottles, 98 books").toArray //Array(99,98) 找到字符串中首个匹配性,可以使用findFirstIn
替换首个匹配项或者全部匹配项:val matches=numPattern.findFirstIn("99 bottles, 98 books") //Some("98")
numPattern.replaceFirstIn("99 bottles,98 books","xx") //xx bottles,98 books numPattern.replaceAllIn("99 bottles,98 books","xx") //xx bottles,xx books
9. 正则表达式组
分组可以方便获取正则表达式的子表达式。在想提取的子表达式两侧加上圆括号。要匹配组,可以把正则表达式对象当做“提取器”使用:val numitemPattern="([0-9]+) ([a-z]+)".r
要从多个匹配项中提取分组内容,可以使用for语句:val numitemPattern(num,item)="99 books"//将num设置为“99”,item设为"books"
for(numitemPattern(num,item)<-numitemPattern.findAllIn("99 books,98 bottles")) 处理num和item