文章目录
- 文件IO操作
文件IO操作
-
读取文件
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25/** * 如果出于某种原因eachLine抛出异常,该方法能够确保资源正确地关闭, * 这适用于所有Groovy添加的I/O资源方法 */ new File(".", 'test.txt').eachLine { line -> println line } new File(".", 'test.txt').eachLine { line, nb -> println "Line $nb: $line" } def list = new File(".", 'test.txt').collect {it} println list def array = new File(".", 'test.txt') as String[] println array //获取文件的所有字节到字节数组 byte[] contents = new File(".", 'test.txt').bytes println contents def is = new File(".", 'test.txt').newInputStream() // do something ... is.close() //需要手动关闭流 new File(".", 'test.txt').withInputStream { stream -> // do something ... }
-
写入文件
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18//自动创建文件并写入 new File(".", 'test_writer.txt').withWriter('utf-8') { writer -> writer.writeLine 'dddd' writer.writeLine 'eeee' writer.writeLine 'ffff' } //等价以上的方式 new File(".", 'test_writer.txt') << '''dddd eeee ffff''' def os = new File(".", 'test_writer.txt').newOutputStream() // do something ... os.close() //需要手动关闭 new File(".", 'test_writer.txt').withOutputStream { stream -> // do something ... }
-
遍历目录
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35import groovy.io.FileType import groovy.io.FileVisitResult //在目录的每一个文件直行闭包代码 new File(".").eachFile { file -> println file.name } println("==============") //查找.groovy后缀的文件 new File(".").eachFileMatch(~/.*.groovy/) { file -> println file.name } println("==============") //在指定目录递归查找,并在每一个文件和目录直行闭包代码 new File(".").eachFileRecurse { file -> println file.name } println("==============") //在指定目录递归查找,并在每一个文件直行闭包代码 new File(".").eachFileRecurse(FileType.FILES) { file -> println file.name } println("==============") //更复杂的遍历,需要设置一个特殊的标志指示这个遍历要做什么。 new File(".").traverse { file -> if (file.directory && file.name=='bin') { //如果当前file是一个目录或者它的名字是 bin ,则停止遍历 FileVisitResult.TERMINATE } else { //打印文件名并继续遍历 println file.name FileVisitResult.CONTINUE } }
-
调用外部进程
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13//在外部process执行`ls`命令,execute()方法返回一个java.lang.Process对象 def process = "ls -l".execute() //读取文本并打印 println "${process.text}" println "==========================" def process2 = "ls -l".execute() //遍历命令进程的输入流 process2.in.eachLine { line -> //打印每一行输入流 println line }
-
对象序列化
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.jannal.io //在外部process执行`ls`命令,execute()方法返回一个java.lang.Process对象 def process = "ls -l".execute() //读取文本并打印 println "${process.text}" println "==========================" def process2 = "ls -l".execute() //遍历命令进程的输入流 process2.in.eachLine { line -> //打印每一行输入流 println line }
最后
以上就是伶俐小鸽子最近收集整理的关于Groovy笔记(四)之IO文件IO操作的全部内容,更多相关Groovy笔记(四)之IO文件IO操作内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复