第十二章 gradle自动化构建系列文章 之 gradle中的文件api
查看 “Android自动化构建系列” 全部文章
garadle 同样为我们提供了问价拷贝的api,通过 copy方法轻松实现拷贝,优点相对于groovy中的操作更加的简单,但是缺点是所有的文件操作的范围无法超出项目工程的范围
1. 获取文件路径相关的api
在子project中运行如下代码
//获取根工程的绝对路径
println "the root path is ${getRootDir().absolutePath}"
//获取工程build文件的绝对路径
println "the build path is ${getBuildDir().absolutePath}"
//获取项目的绝对路经
println "the Project path is ${getProjectDir().absolutePath}"
运行结果:
> Configure project :mylibrary
the root path is G:\house\app\android\wuye
the build path is G:\house\app\android\wuye\mylibrary\build
the Project path is G:\house\app\android\wuye\mylibrary
方法名称 | 作用 |
---|---|
getRootProject | 获取根项目的路径 |
getBuildDir | 获取当前项目的build文件所在的目录 |
getProjectDir | 获取当前项目的路径 |
2. file(String path) ,path 是相对于当前工程来说的,可以传入一个相对当前工程的相对路径
示例演示,使用gradle中的api去读取文件,在子project中编写代码读取rootproject中文件的内容
- 在mylibrary的
build.gradle
中定义方法并读取 文件的内容,注意在gradle的编程中捕获的异常优先使用gradle中的异常类
println getContent(getProjectDir().parent+"/commonConfig.gradle")
def getContent(String path) {
try {
def file = file(path)
return file.text
} catch (GradleException e) {
println "file not find !"
return null
}
}
运行结果:
成功的读取到了文件中的内容,file() 方法读取文件路径是相对于当前的项目来说的
3. ConfigurableFileCollection files(Object… paths); ,接收一个不定长的参数(数组),最终转换成一个file类型的ConfigurableFileCollection集合
这里暂时不做演示了
4. copy{ form xxxxx,into xxx} 实现文件的拷贝 ,form后面接收一个file类型的对象,into 可以接收file 也可以是String类型的##
示例,将工程根目录下的文件拷贝到app的build目录下,效果如下
在mylibrary.build文件中实现代码如下:
copy{
from file(getRootDir().absolutePath+"/appNewFeature.properties")
into getRootProject().project("app").getBuildDir().absolutePath
}
运行后完美实现拷贝
copy方法不仅可以拷贝文件,还可实现文件夹的拷贝
当我们打包生成apk的时候我们可以将整个的apk目录备份到指定的文件区域
在mylibrary.build文件中实现代码如下:
//将一个文件夹拷贝到另一文件夹
copy{
from file(getRootProject().project("app").getBuildDir().absolutePath+"/outputs/apk")
into getRootProject().getBuildDir().absolutePath
}
运行结果实现了将文件apk拷贝到了根工程的build文件夹中