Gradle系列之二 Groovy对文件的操作
Groovy对文件的操作
对文件的遍历
假设文件的原始内容为:
复制代码
1
2
3hello,world 这里是北京 andorid and ios are good system
第一种方法:使用 eachLine()
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13//1.1 new 一个File def file = new File(filepath) //1.2 groovy对文件的遍历 file.eachLine { //打印每一行内容 line -> println line } //输出 hello,world 这里是北京 andorid and ios are good system
第二种方法:使用File的getText()
复制代码
1
2
3
4
5
6def content = file.getText() println content //输出 hello,world 这里是北京 andorid and ios are good system
是不是更简单,直接调用一个方法就OK了,比Java操作文件要简单太多了吧
第三种方法:使用 file.readLines()方法
复制代码
1
2
3
4
5
6
7
8
9
10
11def list = file.readLines() list.collect { println it } println "文件有" + list.size() + "行" //输出 hello,world 这里是北京 andorid and ios are good system 文件有3行
是不是很方便,readLines()函数直接把文件内容以行为单位读取到一个List中,这样操作就更方便了
第四种方法:读取文件部分内容
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13//读取前20个字符 def reader = file.withReader { reader -> char[] buffer = new char[20] reader.read(buffer) return buffer } println reader //输出 hello,world 这里是北京 an
如何拷贝文件?
我们写一个方法,把刚才的文件拷贝到另一个文件中去,代码如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24def copy(String sourcePath, String destPath) { try { //1 创建目标文件 def destFile = new File(destPath) if (!destFile.exists()) { destFile.createNewFile() } //2 开始拷贝 new File(sourcePath).withReader { reader -> def lines = reader.readLines() destFile.withWriter { writer -> lines.each { //把每一行都写入到目标文件中 line -> writer.append(line+"rn") } } } return true } catch (Exception e) { return false } }
读写对象
有时候我们会有这样的需求,需要把我们的bean对象写入到文件中,用到的时候再读出来,下面我们就来实现这样的功能,代码如下:
复制代码
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
35
36
37
38
39
40
41
42//将一个对象写入到文件中 def saveObject(Object object, String path) { try { //1 首先创建目标文件 def destFile = new File(path) if (!destFile.exists()) { destFile.createNewFile() } destFile.withObjectOutputStream { out -> out.writeObject(object) } return true } catch (Exception e) { } return false; } //从一个文件中读到bean def readObject(String path) { def obj = null try { //1 先判断文件是否存在 def file = new File(path) if (!file.exists()) { return null } //2 从文件中读取对象 file.withObjectInputStream { reader -> obj = reader.readObject(); } return obj } catch (Exception e) { } return null }
Groovy对xml文件的操作
复制代码
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/** test.xml 文件的内容如下: <langs type="current"> <language1>Java</language1> <language2>Groovy</language2> <language3>JavaScript</language3> </langs> */ //一行代码就解析了xml def langs = new XmlParser().parse("test.xml") //打印出node的属性 println langs.attribute('type') //对xml文件的遍历 langs.each { println it.text() } //输出 current Java Groovy JavaScript
以上就是groovy对文件的操作
posted on
2018-11-13 13:11
九路313 阅读(
...) 评论(
...)
编辑
收藏
转载于:https://www.cnblogs.com/start1225/p/9943541.html
最后
以上就是尊敬羊最近收集整理的关于Gradle系列之二 Groovy对文件的操作的全部内容,更多相关Gradle系列之二内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复