Gradle学习[5]——文件操作
本文会列举几个Gradle中常用的文件操作方式,在Groovy中不能这样操作,需要引入gradle-core-api-7.5.jar
。
文件操作
在Gradle中可以使用Project.file(java.lang.Object)
方法(Project可省略),指定文件路径获取文件对象来进行操作,对象API为Java的File对象。
1 2 3 4 5 6 7 8 9
| File configFile = file('src/conf.xml') configFile.createNewFile();
configFile = file('D:\\conf.xml') println(configFile.createNewFile())
configFile = new File('src/config.xml') println(configFile.exists())
|
文件集合
在Gradle中可以使用Project.files(java.lang.Object[])
方法获取文件集合对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def collection = files('src/test1.txt',new File('src/test2.txt'),['src/test3.txt', 'src/test4.txt']) collection.forEach(){File it -> it.createNewFile() println it.name } Set set1 = collection.files Set set2 = collection as Set List list = collection as List for (item in list) { println item.name } def union = collection + files('src/test5.txt') def minus = collection - files('src/test3.txt') union.forEach(){ println it.name }
|
文件树
文件树能够表示文件的层级结构,文件树对象是从文件集合继承过来的,具有文件集合的所有功能。
在Gradle中可以使用Project.fileTree(java.util.Map)
方法创建文件树对象。
1 2 3 4 5 6 7 8 9 10
| tree = fileTree('src/main').include('**/*.java')
tree = fileTree('src/main') { include '**/*.java' } tree = fileTree(dir: 'src/main', include: '**/*.java') tree.each { println file println file.name }
|
对Zip压缩包创建文件树对象
1
| FileTree zip = zipTree('someFile.zip')
|
对Tar压缩包创建文件树对象
1
| FileTree tar = tarTree('someFile.tar')
|
文件复制
在Gradle中可以使用默认提供的Copy任务来完成文件复制操作。
1 2 3 4
| task 'copyTask'(type:Copy) { from './Groovy' into './Groovy1' }
|
它还可以复制压缩包中的文件
1 2 3 4 5 6 7 8 9 10
| task copyTask(type: Copy) { from 'src/main/webapp' from 'src/staging/index.html' from zipTree('src/main/assets.zip') into 'build/explodedWar' }
|
还可以指定包含、排除条件
1 2 3 4 5
| task copyTaskWithPatterns(type: Copy) { from 'src/main/webapp' into 'build/explodedWar' include '**/*.html' include '**/*.jsp' exclude { details -> details.file.name.endsWith('.html') } }
|
还可以进行重命名操作
1 2 3 4 5 6
| task rename(type: Copy) { from 'src/main/webapp' into 'build/explodedWar' rename { String fileName -> fileName.replace('-staging-', '') } }
|
除了在定义任务时指定type外,还有其他的使用方式,如在一个task中
1 2 3 4 5 6 7 8 9 10
| task copyMethod { doLast { copy { from 'src/main/webapp' into 'build/explodedWar' include '**/*.html' include '**/*.jsp' } } }
|
或者直接在脚本最外层Project对象中
1 2 3 4 5
| copy { from file('src/main/resources/ddd.txt') into this.buildDir.absolutePath }
|
文件归档
可以将多个文件打成War、Jar、Zip、Tar包,对应的包都有对应的任务实现了。
Zip包
1 2 3 4 5
| task myZip(type: Zip) { from 'src/main‘ into ‘build’ //保存到build目录中 baseName = 'myGame' }
|