1. 程式人生 > >Android中gradle指令碼 刪除目錄 批改目錄 修改檔案字串等操作

Android中gradle指令碼 刪除目錄 批改目錄 修改檔案字串等操作

原文地址:http://www.68idc.cn/help/mobilesys/android/20160507613407.html

Android中gradle指令碼 刪除目錄 修改目錄 修改檔案字串等操作
//編碼格式
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}

//定義全域性變數
ext{
NAME="test"
}

//讀取gradle配置檔案
def initBuildPath() {
Properties properties = new Properties()
File propertyFile = new File(rootDir.getAbsolutePath() + "/local.properties")
properties.load(propertyFile.newDataInputStream())
ext.sdkDir = properties.getProperty('sdk.dir')
ext.ndkDir = properties.getProperty('ndk.dir')
}

//讀取檔案並替換字串

def fileReader(path, oldStr, newStr) {
def readerString = "";
new File(path).withReader('UTF-8') { reader ->
reader.eachLine {
if (it.find(oldStr)) {
it = it.replace(oldStr, newStr)
}
readerString <<= it
readerString << '\n'
}
return readerString
}
}

//寫檔案

def fileWrite(path, stringBuffer) {
new File(path).withWriter('UTF-8') {
within ->
within.append(stringBuffer)
}
}

//copy src 目錄

task copyPackage(type: Copy) {
initBuildPath()
from 'src'
into SRC_TEMP
// 剔除不需要的檔案
exclude '*values-zh-rCN', '*values-zh-rTW', '*values-th', '*values-ko'
}

//修改目錄

task moveToTest(type: Copy) {
// println("開始移動到test")
from JAVA_DIR
into JAVA_DIR_TEST
filter { String line ->
if (line.find('package com.main;')) {
//替換字串
line = line.replace("package com.main;", "package com.main.test;")
}
"$line"
}
//刪除原目錄
doLast {
File file1 = new File(rootDir.getAbsolutePath() + '\\app\\' + JAVA_DIR);
file1.deleteDir();
}
}

//替換檔案的字串

task replaceConstants << {
def strBuffer = 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);
}

//執行命令列

task createR(type: Exec) {
workingDir 'E:\\SDK\\build-tools\\23.0.2\\'
commandLine 'cmd', '/c', 'aapt package -f -m -J ' + r檔案要存放的目錄 + " -S v7的res檔案 -S res檔案 -M manifest檔案 -I android.jar檔案 --auto-add-overlay"
}

//apk編譯之前執行taskA

preBuild.dependsOn taskA