Scala OS操作

OS操作

遍历目录

1
2
3
4
5
6
7
8
9
10
import java.io.File
// 1 depth walk
new File(dir_path).listFiles() //返回一个数组,包含该目录下所有文件/目录的File对象,只做1级深度
new File(dir_path).list() // return the files/directories name below `dir_path`

/** or **/
import scala.reflect.io.Path
val ap = Path(dir_path)
ap.walk.toList // walk recursively, all depth to the leaf files.
ap.walkFilter(cond: Path=>Boolean)

增删查改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.File
new File("tmp").mkdir() // mkdir tmp
new File("tmp.txt").createNewFile() // touch tmp
new File("tmp").delete() // rm -rf tmp
new File("tmp.txt").renameTo(new File("sht.txt")) //rename tmp.txt fuck.txt

new File("tmp.txt").is* // 查询是否文件、目录
new File("tmp.txt").can* // 查询是否可写可读可执行
new File("tmp.txt").exists //查询是否存在

/** or **/
import scala.reflect.io.Path
Path("tmp").createDirectory() // mkdir tmp
Path("tmp.txt").createFile() // touch tmp.txt
Path("tmp").delete(); Path("tmp").deleteRecursivly()// rm -rf tmp
Path("tmp.txt").renameTo(new File("sht.txt")) //rename tmp.txt fuck.txt
Path("tmp.txt").is* // 查询是否文件、目录
Path("tmp.txt").can* // 查询是否可写可读可执行
Path("tmp.txt").exists

文件名操作

1
2
3
4
5
import scala.reflect.io._

Path("fuck.txt").parent // 拿到父目录
Path("fuck.txt").toAbsolute //拿到绝对路径
Path("fuck.txt").extension //拿到文件后缀

Process

需要调用外部命令时, import scala.sys.process._

正常调用

1
Process("<cmd>") !!

处理命令输出

1
2
3
4
5
6
val logger = ProcessLogger(line => if(line.contain("shit")) println("Got a shit"))
//logger 逐行处理
Process("cat shitgamedamnit").!(logger)

//或者整体处理
val retLog = Process("ls").!!