Scala文件操作

 

本文记录了Scala对文件的操作,主要包括遍历文件、文件复制、递归读取文件、序列化和反序列化。

 

import java.io._

import scala.io.Source

object FileOperation {

    def main(args: Array[String]): Unit = {

        // 遍历文件的每一行
        // 01 使用source.getLines()返回的迭代器
        val source01 = Source.fromFile("D:/test.txt", "UTF-8")
        val lineIterator01 = source01.getLines()
        for (line <- lineIterator01) println(line)

        // 02 将Source.getLines返回的迭代器,转换成数组
        val source02 = Source.fromFile("D:/test.txt", "UTF-8")
        val lineIterator02 = source02.getLines().toArray
        for (line <- lineIterator02) println(line)

        // 03 调用Source.mkString,返回文本中所有的内容
        val source03 = Source.fromFile("D:/test.txt", "UTF-8")
        println(source03.mkString)
        source03.close()

        // 04 遍历文件中的每个字符
        val source04 = Source.fromFile("D:/test.txt", "UTF-8")
        for (c <- source04) println(c + " ")

        // 05 从URL中读取字符
        val source05 = Source.fromURL("https://www.hao123.com", "UTF-8")
        for (c <- source05) print(c + " ")

        // 06 从字符串中读取
        val source06 = Source.fromString("Hello World")
        for (c <- source06) print(c + " ")

        // 07 文件copy
        val in = new FileInputStream(new File("D:/test.txt"))
        val out = new FileOutputStream(new File("D:/test_copy.txt"))
        val buf = new Array[Byte](1024)
        in.read(buf)
        out.write(buf, 0, 1024)
        in.close()
        out.close()

        // 08 写文件
        val pw = new PrintWriter("D:/test_write.txt")
        pw.println("hello world")
        pw.close()

        // 09 递归遍历子目录
        val iterator = recursion(new File("D:/test"))
        for (dir <- iterator) println(dir)

        // 序列化
        val angus = new P("angus")
        val oos = new ObjectOutputStream(new FileOutputStream("D:/test/angus.obj"))
        oos.writeObject(angus)
        oos.close()

        // 反序列化
        val ois = new ObjectInputStream(new FileInputStream("D:/test/angus.obj"))
        val restoredAngus = ois.readObject().asInstanceOf[P]
        println(restoredAngus.name)
    }


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


    class P(val name: String) extends Serializable


}

 

posted @ 2018-07-19 17:35  胜迹寻芳  阅读(431)  评论(0编辑  收藏  举报