Scala基础篇(三)文件操作案例

读取文件的所有行,调用scala.io.Source对象的getLines方法:

import scala.io.Source  
val fileName = "/home/spark/derby.log"
val source = Source.fromFile(fileName)
val lines = source.getLines.toBuffer
for(line <- lines) println(line)
lines.foreach(println _)		// 更符合scala风格

也可以对getLines(类型为Iterator[String])应用toArray或toBuffer方法,将这些行放到数组或缓冲当中:

val lines = source.getLines.toArray  
val lines = source.getLines.toBuffer

或者将文件内容读成一个字符串

val lines = source.mkString

Scala没有内建的对写入文件的支持;
需要使用java的包java.io.PrintWriter,实现数据写入文件中
 

import scala.io.Source
import java.io.PrintWriter

val lines = Source.fromFile("/home/spark/derby.log").mkString
val out = new PrintWriter("output.log")
for (i <- 1 to 10){
  out.print(i + "+")		// 写入一个特殊的文件头
}
out.println
out.println(lines)
out.close()

对文件的分析切割使用了java中的正则

package day03_class

import java.io.PrintWriter
import java.util.regex.Pattern

import scala.io.Source

object HomeWork3 {
  def main(args: Array[String]): Unit = {
      println("null"!=null)
      val filePath="C:\\Users\\Administrator.DESKTOP-839UKR6\\Desktop\\03Day\\access.log"
      val r= Source.fromFile(filePath).bufferedReader()
      val out = new PrintWriter("output.log")
     var line=""
     val pattern= Pattern.compile("""(.+) -- \[(.+)\] "(.+)" (\d+) (\d+)  "(.+)" "(.+)"""")
     while(true){
          line = r.readLine()
         if(line==null){return }
          var res = pattern.matcher(line)
        if (res.matches()) {
          out.println(res.group(0))
        } else {
          println("error")
        }
    }
    r.close()
    out.close()
    println(line)
   // 87.124.46.87 -- [2016-01-01 00:00:01] "GET /admin/login.php HTTP/1.1" 200 0  "-" "sssss"
  }
}

正则表达式 — — 捕获组

捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或显式命名的组里,方便后面引用。
例如: /(a)(b)(c)/中的捕获组编号为
组0: abc
组1: a
组2: b
组3: c
其中,组0是正则表达式整体匹配结果,组 1 2 3 才是子表达式匹配结果

 

元字符、反义词、限定符

代码	说明
.	匹配除换行符以外的任意字符
\w	匹配字母或数字或下划线或汉字
\s	匹配任意的空白符
\d	匹配数字
\b	匹配单词的开始或结束
^	匹配字符串的开始
$	匹配字符串的结束
代码	说明
\W	匹配任意不是字母,数字,下划线,汉字的字符
\S	匹配任意不是空白符的字符
\D	匹配任意非数字的字符
\B	匹配不是单词开头或结束的位置
[^x]	匹配除了x以外的任意字符
[^aeiou]	匹配除了aeiou这几个字母以外的任意字符

代码

说明

*

重复0次或更多次

+

重复1次或更多次

重复零次或一次

{n}

重复n次

{n,}

重复n次或更多次

{n,m}

重复n到m次

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值