• Scala的文件读写操作与正则表达式


    在本篇博客中你将会学习并了解常用的文件处理任务,例如读取文件的一行文本,本博客的要点包含:

    1. Source.fromFile(...).getLines.toArray 输出文件所有行
    2. Source.fromFile(...).mkString 以字符串形式输出文件内容
    3. 将字符串转换为数字,可以使用toInt或toDouble方法
    4. 使用java的PrintWriter写入文本文件
    5. “正则”.r是一个Regex对象
    6. 若你的正则表达式包含反斜杠或者引号,请用"""..."""
    7. 正则模式包含分组,可以使用for(regex(变量1...,变量2)<- 字符串)

    本篇博客要点如下:

    读取行

    // 读取文件所有的行,可以调用scala.io.Source对象的getLines方法:
    val source = Source.fromFile("a.txt","utf-8")
    val lineIterator = source.getLines
    结果是迭代器可以使用for循环处理这些行
    for(i <- lineIterator) println(i)
    也可以使用迭代器应用toArray或toBuffer方法,将这些行放到数组力或者数组缓冲行中,若想将读取的的文件作为一个字符串,只需val conents = source.mkString
    下面是简单的代码实例:读取桌面上的a.txt
    
    object ReadFile {
      def main(args: Array[String]): Unit = {
        val read = new ReadFile()
        val resource: String = "C:\Users\DonnieGao\Desktop\a.txt"
        val encode = "UTF-8"
        read.readFile(resource, encode)
        println(read.readFileToStr(resource, encode))
      }
    }
    
    class ReadFile {
      /**
        * 一行行读取文件的内容
        *
        * @param resource 文件路径
        * @param code     文件编码格式
        */
      def readFile(resource: String, code: String): Unit = {
        var source: BufferedSource = null
        try {
          // 获取文件的Source对象,第一个参数是文件的路径,第二个文件的编码格式
          source = Source.fromFile(resource, code)
          val lineIterator = source.getLines()
          while (true) {
            if (lineIterator.hasNext) {
              println(lineIterator.next())
            } else {
              return
            }
          }
        } finally {
          // 释放资源
          source.close()
        }
      }
    
      /**
        * 将文本文件所有内容作为字符串
        *
        * @param resource 文件路径
        * @param code     文件编码格式
        * @return
        */
      def readFileToStr(resource: String, code: String): String = {
        // 获取文件的Source对象,第一个参数是文件的路径,第二个文件的编码格式
        var source: BufferedSource = null
        try {
          source = Source.fromFile(resource, code)
          source.mkString
        } finally {
          source.close()
        }
      }
    }
    
    

    读取字符

    要将文件中读取单个字符,可以把Source对象当作迭代器,若仅仅只是想查看字符可以调用Source对象的buffered方法。

    读取词法单元和数字

    读取源文件中所有空格隔开的词法单元
    val tokens = source.mkString.split("\s+")
    若有个基本都是浮点型的文件,可以将其读取到数组中:
    val numbers = for (w <- tokens) yield w.toDouble 或者也可 
    val numbers = token.map(_.toDouble)
    

    读取二进制文件

    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进行文件写入操作例如使用java.io.PrintWriter

      /**
        * Scala写入文借助java的PrintWriter
        */
      def write(): Unit = {
        val out = new PrintWriter("C:\Users\DonnieGao\Desktop\test.txt")
        for (i <- 0 to 100) out.println(i)
        out.close()
      }
    

    访问文件目录

    Scala中没有直接访问某个目录下的所有文件的方式或者递归遍历有目录的类

      /**
        * 使用java列举下所有的文件夹
        * @param dir 文件目录路径
        */
      def dir(dir:String) = {
        val dirFile = new File(dir)
       val arrayFile= dirFile.listFiles()
        for (i <- arrayFile){println(arrayFile.toBuffer)}
      }
    

    序列化

    在java中声明一个可以被序列号的类通常是下面这种:

    public class Person implements java.io.Serializable {
        private static final long serialVersionUID = 4436475322569107137L;
    }
    
    Scala中声明一个可以被序列化的类通常是下面这种:
    @SerialVersionUID(12356L) class ReadFile extends Serializable {
        
    }
    

    正则表达式

    Scala中提供了正则操作处理scala.util.matching.Regex让这件事情可以变得简单。构造一个Regex对象,用String类的r方法即可

    object RegexDemo {
    
      def main(args: Array[String]): Unit = {
        // 初始化正则对象
        val numPattern = "[0-9]+".r
        val regex = "13 welcome to beijing"
        // findAllIn方法返回遍历所有匹配的迭代器,可以在for循环中使用
        for (matchString <- numPattern.findAllIn(regex)) {
          println(matchString)
        }
        // 查询字符串首个匹配项
        println(numPattern.findFirstIn(regex))
        // 检查某个字符串的开始部分能匹配,可以使用findPrefixOf
        println(numPattern.findPrefixOf(regex))
      }
    
  • 相关阅读:
    mongodb单机搭建
    zeus部署
    hive单机部署
    datax部署
    hadoop/hbase/hive单机扩增slave
    读取Jar中的json文件
    Mybatis 一对多 简单映射配置
    java/kotlin 读取文件、写入文件
    ES6中Json、String、Map、Object之间的转换
    java 客户端发起http请求2
  • 原文地址:https://www.cnblogs.com/codegeekgao/p/9627644.html
Copyright © 2020-2023  润新知