例子:
三种方式,使用
task file{
// relative path
File configFile = file('build.gradle')
println 'relative path: ' + configFile
// Using an absolute path
configFile = file(configFile.absolutePath)
println 'absolute path: ' + configFile.absolutePath + ' = ' + configFile
// Using a File object with a relative path
configFile = file(new File('build.gradle'))
println 'file object: ' + configFile
}
输出:
relative path: C:\temp\quickstart\groovy\build.gradle
absolute path: C:\temp\quickstart\groovy\build.gradle = C:\temp\quickstart\groovy\build.gradle
file object: C:\temp\quickstart\groovy\build.gradle
文件集合的创建方式和使用
FileCollection collection = files('build.gradle', new File('other.gradle'), ['settings.gradle', '.gradle/6.0/gc.properties'])
println "collection: " + collection
collection.each {File file ->
println 'file name:' + file.name
}
输出:
这个元素为File的文件集合可以转换成其他的Groovy数据结构:
// Convert the collection to various types
Set set = collection.files
Set set2 = collection as Set
List list = collection as List
String path = collection.asPath
File file = collection.singleFile
File file2 = collection as File
// 也可以使用代码往集合里添加或者删除元素
def union = collection + files('src/file3.txt')
def different = collection - files('src/file3.txt')
文件集合的自定义实现方式
task file {
File srcDir
// Create a file collection using a closure
FileCollection collection = files { srcDir.listFiles() }
srcDir = file('src')
println "Contents of $srcDir.name"
collection.collect { relativePath(it) }.sort().each { println it }
srcDir = file('.gradle')
println "Contents of $srcDir.name"
collection.collect { relativePath(it) }.sort().each { println it }
}
输出:
Contents of src
src\main
src\test
Contents of .gradle
.gradle\6.0
.gradle\buildOutputCleanup
文件树
文件树是按层次结构排序的文件集合。例如,文件树可能表示一个目录树或 ZIP 文件的内容。它通过 FileTree 接口表示。FileTree 接口继承自 FileCollection,所以你可以用对待文件集合一样的方式来对待文件树。Gradle 中的几个对象都实现了 FileTree 接口,例如 source sets。
测试:
task file {
FileTree tree = fileTree(dir: 'src/main')
tree.each {
File file -> println file.name
}
FileTree tree2 = fileTree(dir: '.gradle')
List list = tree2 as List
list.each({
println it
})
}
输出:
Person.java
resource.xml
C:\temp\quickstart\groovy.gradle\6.0\executionHistory\executionHistory.bin
C:\temp\quickstart\groovy.gradle\6.0\executionHistory\executionHistory.lock
C:\temp\quickstart\groovy.gradle\6.0\fileChanges\last-build.bin
C:\temp\quickstart\groovy.gradle\6.0\fileHashes\fileHashes.bin
C:\temp\quickstart\groovy.gradle\6.0\fileHashes\fileHashes.lock
C:\temp\quickstart\groovy.gradle\6.0\gc.properties
C:\temp\quickstart\groovy.gradle\buildOutputCleanup\buildOutputCleanup.lock
C:\temp\quickstart\groovy.gradle\buildOutputCleanup\cache.properties
C:\temp\quickstart\groovy.gradle\buildOutputCleanup\outputFiles.bin
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
本文分享 CSDN - 汪子熙。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。