Scala中遍历文件、删除文件和目录

目前Scala没有“正式的”用来访问某个目录中的所有文件,或者递归地遍历所有目录的类,可以借助java的File类来实现文件目录的遍历和文件操作。

  1. import java.io.File  
  2. /** 
  3.  * 20170309 
  4.  * 目录操作 
  5.  */  
  6.   
  7. object dir {  
  8.   
  9.   def main(args: Array[String]) {  
  10.     val path: File = new File("C:/Users/wei/ScalaWorkspace/learn0305")  
  11.     for (d <- subdirs(path))  
  12.       println(d)  
  13.   }  
  14.   
  15.   //遍历目录  
  16.   def subdirs(dir: File): Iterator[File] = {  
  17.   
  18.     val children = dir.listFiles.filter(_.isDirectory())  
  19.     children.toIterator ++ children.toIterator.flatMap(subdirs _)  
  20.   
  21.   }  
  22.   
  23.   //删除目录和文件  
  24.   def dirDel(path: File) {  
  25.     if (!path.exists())  
  26.       return  
  27.     else if (path.isFile()) {  
  28.       path.delete()  
  29.       println(path + ":  文件被删除")  
  30.       return  
  31.     }  
  32.   
  33.     val file: Array[File] = path.listFiles()  
  34.     for (d <- file) {  
  35.       dirDel(d)  
  36.     }  
  37.   
  38.     path.delete()  
  39.     println(path + ":  目录被删除")  
  40.   
  41.   }  
  42.   


猜你喜欢

转载自blog.csdn.net/grl5979/article/details/80816252