一、读取行
import scala.io.Source
val source = Source.fromFile("D:\\documents\\Scala\\MyDemo\\t.txt", "UTF-8")
val lineIterator = source.getLines() //获取文件行的迭代器
for(l <- lineIterator){
println(l)
}
val array = source.getLines().toArray //把行放到Array中
for(l <- array){
println(l)
}
val context = source.mkString //把整个文件读取成一个字符串
println(context)
source.close()
读取文件这里不能重复读取,只显示一遍文本内容
111111111
22222222222222222
3333333333
二、读取字符
import scala.io.Source
val source = Source.fromFile("D:\\documents\\Scala\\MyDemo\\t.txt","UTF-8")
for(c <- source){ //一个字符一个字符迭代 Source扩展自 Iterator[Char]
print(c)
}
val iter = source.buffered //使用bufferd方法,用head获取字符
while(iter.hasNext){
if(iter.head == 'a'){
iter.next()
iter.next()
print(iter.head)
}
else{
iter.next()
}
}
三、读取词法单元和数字
import scala.io.Source
val source = Source.fromFile("D:\\sxt\\documents\\Scala\\MyDemo\\num.txt", "gbk")
val lines = source.getLines() //以行读取
for(l<- lines){
val tokens = l.split("\\s+") //将每行数据以空格隔开
for(i<- tokens){
print(i+",")
}; println()
val numbers = tokens.map(_.toDouble) //将分割的字符串转换成double类型
for(n<- numbers){
print(n+"|")
}; println()
val numbers1 = for(n<- tokens) yield n.toDouble //将分割的字符串转换成double类型
for(n <- numbers1){
print(n+"-")
}; println()
}
四、从URL或其他源读取
import scala.io.Source
val source1 = Source.fromURL("http://www.baidu.com","UTF-8")
println(source1)
val source2 = Source.fromString("Hello World")
println(source2.mkString)
val source3 = Source.stdin
println(source3.mkString)
五、读取二进制文件
Scala没有读取二进制文件的方法,需要使用Java类库,
import java.io.File
val file = new File("D:\\\\sxt\\\\documents\\\\Scala\\\\MyDemo\\\\t.txt")
val in = new FileInputStream(file)
val bytes = new Array[Byte](file.length.toInt)
in.read(bytes)
for(i <- 0 until bytes.length) print(bytes(i))
in.close()
结果:
六、写入文本文件
val value = 100
val out = new PrintWriter("t1.txt")
for(i <- 0 to 100) out.println(i)
out.printf("%d ", value.asInstanceOf[AnyRef]) //格式化输出需要转换成 AnyRef
out.print("%d".format(value)) //通过String的format的方法完成格式化输出
out.close()
结果:
在项目工程目录下,生成t1.txt文件
七、访问目录
八、序列化
九、进程控制
十、正则表达式
val numPattern = "[0-9]+".r //通过 String的 r方法
val wsnumwsPattern = """\s+[0-9]+\s+""".r //"""...""" 原始字符串可包含反斜线或引号,不需要转义 "\\s+[0-9]+\\s+"
for(matchString <- numPattern.findAllIn("99 apples, 87 bottles")) println(matchString) //findAllIn返回所有匹配项的迭代器
val matches = numPattern.findAllIn("99 apples, 87 bottles").toArray //转换成数组
for(m<- matches) println(m)
val m1: Option[String] = wsnumwsPattern.findFirstIn("99 apples, 87 bottles") //获得第一个匹配项
println(m1)
val mp = numPattern.findPrefixOf("99 apples, 87 bottles") //获取开始部分匹配的
println(mp)