Appearance
文件操作基础
Gradle 提供了丰富的文件 API,用于在构建脚本中处理文件和目录。
定位文件
kotlin
// project.file():相对于项目根目录
val configFile = file("src/config/app.yml")
// layout API(推荐,懒加载)
val srcDir = layout.projectDirectory.dir("src")
val buildDir = layout.buildDirectory.dir("generated")
val outputFile = layout.buildDirectory.file("output.txt")文件集合
kotlin
// fileTree:目录下的文件集合(支持过滤)
val sources = fileTree("src/main/java") {
include("**/*.java")
exclude("**/generated/**")
}
// files():任意文件的集合
val classpath = files(
"lib/a.jar",
"lib/b.jar",
configurations["compileClasspath"]
)
// 遍历文件集合
sources.forEach { file ->
println(file.absolutePath)
}路径与 URI
kotlin
// 获取绝对路径字符串
val path = file("src").absolutePath
// 获取 URI
val uri = uri("file://${projectDir}/src")
// 跨平台路径(不推荐拼接路径字符串)
val configDir = file("${rootDir}/config")读写文件
kotlin
tasks.register("processFile") {
val inputFile = file("src/template.txt")
val outputFile = layout.buildDirectory.file("processed.txt")
inputs.file(inputFile)
outputs.file(outputFile)
doLast {
// 读取
val content = inputFile.readText(Charsets.UTF_8)
// 处理
val processed = content
.replace("@VERSION@", project.version.toString())
.replace("@DATE@", java.time.LocalDate.now().toString())
// 写入(自动创建父目录)
val out = outputFile.get().asFile
out.parentFile.mkdirs()
out.writeText(processed, Charsets.UTF_8)
}
}sync 与 copy
kotlin
tasks.register<Copy>("copyResources") {
from("src/main/resources")
into(layout.buildDirectory.dir("resources"))
// 内容过滤
filter<org.apache.tools.ant.filters.ReplaceTokens>("tokens" to mapOf(
"VERSION" to project.version
))
// 排除
exclude("**/*.bak", "**/test*")
// 重命名
rename("(.+)-production.yml", "$1.yml")
}
// sync:类似 copy,但会删除目标目录中多余的文件
tasks.register<Sync>("syncDist") {
from("src/main/resources")
into("dist/resources")
}