Android中gradle脚本 删除目录 修改目录 修改文件字符串等操作

//编码格式

tasks.withType(JavaCompile){

options.encoding='UTF-8'

}

//定义全局变量

ext{

name="test"

}

//读取gradle配置文件

definitBuildPath(){

Propertiesproperties=newProperties()

FilepropertyFile=newFile(rootDir.getAbsolutePath()+"/local.properties")

properties.load(propertyFile.newDataInputStream())

ext.sdkDir=properties.getProperty('sdk.dir')

ext.ndkDir=properties.getProperty('ndk.dir')

}

//读取文件并替换字符串

deffileReader(path,oldStr,newStr){

defreaderString="";

newFile(path).withReader('UTF-8'){reader->

reader.eachLine{

if(it.find(oldStr)){

it=it.replace(oldStr,newStr)

}

readerString<<=it

readerString<<'\n'

}

returnreaderString

}

}

//写文件

deffileWrite(path,stringBuffer){

newFile(path).withWriter('UTF-8'){

within->

within.append(stringBuffer)

}

}

//copysrc目录

taskcopyPackage(type:Copy){

initBuildPath()

from'src'

intoSRC_TEMP

//剔除不需要的文件

exclude'*values-zh-rCN','*values-zh-rTW','*values-th','*values-ko'

}

//修改目录

taskmoveToTest(type:Copy){

//println("开始移动到test")

fromJAVA_DIR

intoJAVA_DIR_TEST

filter{Stringline->

if(line.find('packagecom.main;')){

//替换字符串

line=line.replace("packagecom.main;","packagecom.main.test;")

}

"$line"

}

//删除原目录

doLast{

Filefile1=newFile(rootDir.getAbsolutePath()+'\\app\\'+JAVA_DIR);

file1.deleteDir();

}

}

//替换文件的字符串

taskreplaceConstants<<{

defstrBuffer=fileReader(rootDir.getAbsolutePath()+'\\app\\'+JAVA_DIR_TEST+'\\Test.java',"TEST_FLAG=0","TEST_FLAG=1");

fileWrite(rootDir.getAbsolutePath()+'\\app\\'+JAVA_DIR_TEST+'\\Test.java',strBuffer);

}

//运行命令行

taskcreateR(type:Exec){

workingDir'E:\\SDK\\build-tools\\23.0.2\\'

commandLine'cmd','/c','aaptpackage-f-m-J'+r文件要存放的目录+"-Sv7的res文件-Sres文件-Mmanifest文件-Iandroid.jar文件--auto-add-overlay"

}

//apk编译之前运行taskA

preBuild.dependsOntaskA

相关推荐