scala文件和目录操作

scala文件


1.读取行

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

object HelloWord{
  def main(args:Array[String]):Unit = {
    val fileName = "d:\\scalaTestFile.txt"
    val source = Source.fromFile(fileName)
    val lines = source.getLines
    source.close;//记得要关闭source

    for(line <- lines){
      println(line)
    }
  }
}


也可以对getLines应用toArray或toBuffer方法,将这些行放到数组或缓冲当中。
val lines1 = source.getLines.toArray
val lines2 = source.getLines.toBuffer


将文件内容读成一个字符串:
val lines = source.mkString


2.读取字符

要从文件中读取字符,可以直接把Source对象当做迭代器:
val fileName = "d:\\scalaTestFile.txt"
    val source = Source.fromFile(fileName)
   
    for(c <- source){
      println(c)
    }


如果想查看某个字符,但是不处理掉的话,调用source对象的buffered方法。
    val fileName = "d:\\scalaTestFile.txt"
    val source = Source.fromFile(fileName)
    val iter = source.buffered
   
    while(iter.hasNext){
      if(iter.next == '王'){
        println("wang")
      }else{
        println("-")
      }
    }


3.读取词法单元或数字

通过split方法对转化成行的文件内容进行划分,通过toInt或toDouble方法把字符转化成整数或浮点数。
    val fileName = "d:\\scalaTestFile.txt"
    val source = Source.fromFile(fileName)
    val iter = source.mkString.split("\\s+")
    
    println(iter(0))
    
    val num = for(w <- iter) yield w.toDouble
    
    for(i <- num) println(i)


4.从URL或其它资源读取

import scala.io.Source
import scala.util.control.Breaks._

object HelloWord{
  def main(args:Array[String]):Unit = {
    val source1 = Source.fromURL("http://baidu.com")//URL读取
    val source2 = Source.fromString("hello")//读取给定的字符串-多用于调试
    val source3 = Source.stdin//从标准输入读取
    
    breakable{
        while(source3.hasNext){
          val s3in = source3.next
          if(s3in == 'q'){
            break
          }else{
            println(s3in)
          }
        }
    }
  }
}



5.写入文本

Scala没有內建的对写入文件的支持,要写入文本文件,可以使用java.io.PrintWriter.
import java.io.PrintWriter

object HelloWord{
  def main(args:Array[String]):Unit = {
      val out = new PrintWriter("d:\\testScalaWrite.txt")
      for(i <- 1 to 10){
        out.print(i + "+")
      }
      out.close()
  }
}


6.访问目录

//遍历某目录下所有的子目录
import java.io.PrintWriter
import java.io.File
import scala.reflect.io.Directory

object HelloWord{
  def main(args:Array[String]):Unit = {
      for(d <- subDir(new File("d:\\AAA\\")))
        println(d)
  }
 
  def subDir(dir:File):Iterator[File] ={
    val children = dir.listFiles().filter(_.isDirectory())
    children.toIterator ++ children.toIterator.flatMap(subDir _)
  }
}

//遍历某目录下所有的文件和子文件
  def main(args:Array[String]):Unit = {
      for(d <- subDir(new File("d:\\AAA\\")))
        println(d)
  }
 
  def subDir(dir:File):Iterator[File] ={
    val dirs = dir.listFiles().filter(_.isDirectory())
    val files = dir.listFiles().filter(_.isFile())
    files.toIterator ++ dirs.toIterator.flatMap(subDir _)
  }





>>>>>__以上内容摘自:《快学Scala》  [美]Cay S. Horstmann著   电子工业出版社__<<<<<







  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Scala 实现目录文件 copy 操作的示例代码: ```scala import java.io._ object FileCopy { def main(args: Array[String]): Unit = { val source = new File("path/to/source/directory") val destination = new File("path/to/destination/directory") copyDirectory(source, destination) } def copyDirectory(source: File, destination: File): Unit = { if (source.isDirectory) { if (!destination.exists()) { destination.mkdir() } val files = source.listFiles() for (f <- files) { val newFile = new File(destination.getAbsolutePath + File.separator + f.getName) copyDirectory(f, newFile) } } else { val in = new FileInputStream(source) val out = new FileOutputStream(destination) val buffer = new Array[Byte](1024) var length = in.read(buffer) while (length > 0) { out.write(buffer, 0, length) length = in.read(buffer) } in.close() out.close() } } } ``` 在上述代码中,我们首先定义了源目录和目标目录,然后调用 `copyDirectory` 方法来执行目录文件的复制操作。如果源目录是一个目录,我们会检查目标目录是否存在,如果不存在则创建它,并且遍历源目录中的所有文件和子目录。对于每个文件,我们都会创建一个新的文件对象,并递归调用 `copyDirectory` 方法来复制文件到目标目录中。如果源目录是一个文件,我们会使用 `FileInputStream` 和 `FileOutputStream` 来读取和写入文件内容,并使用一个缓冲区来提高性能。最后,我们关闭输入和输出流并退出方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值