文件操作实战

import scala.io.Source

//文件遍历
object Score extends App {
  //读文件
  val source = Source.fromFile("c://test.txt","UTF-8") //BufferedSource对象
  val lines = source.getLines() //Iterator[String]
  lines.toArray //转为数组
  source.mkString //转为String
  //遍历每一行
  for (line <- lines.toArray){
    println(line)
  }

  //遍历字符
  for (c <- source){
    println(c)
  }

  //URL以及字符串读字符
  val source1 = Source.fromURL("www.baidu.com", "UTF-8")
  val source2 = Source.fromString("www.baidu.com")

  //拷贝文件
  import java.io._
  val file = new File("C:\\test.txt") //java.io.File
  val fis = new FileInputStream(file)
  val fos = new FileOutputStream(new File("C:\\test1.txt"))
  val buf = new Array[Byte](1024)
  fis.read(buf)
  fos.write(buf)

  fis.close()
  fos.close()

  //返回当前目录下所有子目录及递归子目录
  def getSubdirIterator(dir: File): Iterator[File] = {
    val childDirs = dir.listFiles.filter(_.isDirectory)
    childDirs.toIterator ++ childDirs.toIterator.flatMap(getSubdirIterator _)
  }
  val it = getSubdirIterator(new File("C://"))
  for(d <- it){
    println(d)
  }

  //scala序列化、反序列化使用的是java的
  @SerialVersionUID(1L) class Person(val name: String) extends Serializable
  val cys = new Person("cys")

  val oos = new ObjectOutputStream((new FileOutputStream(new File("C://text.txt"))))
  oos.writeObject(cys)
  oos.close()

  val ois = new ObjectInputStream(new FileInputStream(new File("C://text.txt")))
  val cys1 = ois.readObject().asInstanceOf[Person]
  ois.close()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值