目的
想要实现的效果是通过gradle来读取本地的config.json文件并返回JsonObject对象。
思路
因为gradle使用的是Groovy语言。而Groovy又完全兼容Java,所以使用gradle读取本地文件的思路就是利用Java语言实现对文件的操作。
代码
-
读取文件的代码
JSONObject readFileToJson(){ try { File file = new File("${rootDir}/app/config.json") FileReader fileReader = new FileReader(file); String line = null; StringBuilder sb = new StringBuilder() while ( (line = fileReader.readLine()) != null){ sb.append(line) } fileReader.close() print("config.json里的内容为:${sb.toString()}") return new JSONObject(sb.toString()) } catch (IOException | JSONException e) { e.printStackTrace() } return null }
-
完整的build.gradle
里面增加的有详细注释。
import org.json.JSONException import org.json.JSONObject plugins { id 'com.android.application' id 'kotlin-android' } //定义一个函数用来读取app/config.json文件,并将读取的文件内容转换成JSONObject对象。 JSONObject readFileToJson(){ try { File file = new File("${rootDir}/app/config.json") FileReader fileReader = new FileReader(file); String line = null; StringBuilder sb = new StringBuilder() while ( (line = fileReader.readLine()) != null){ sb.append(line) } fileReader.close() print("config.json里的内容为:${sb.toString()}") return new JSONObject(sb.toString()) } catch (IOException | JSONException e) { e.printStackTrace() } return null } android { compileSdkVersion 30 buildToolsVersion "30.0.2" defaultConfig { applicationId "com.wuang.touchdispatchdemo" minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName "1.0" //调用读取文件的函数,返回JSONObject对象 JSONObject jsonObject = readFileToJson() //获取IS_GROUP_LOG的值 boolean IS_GROUP_LOG = jsonObject.optBoolean("IS_GROUP_LOG") //通过buildConfigField定义的变量会在BuildConfig.java中生成相对应的静态变量,我们在java代码中就可以通过BuildConfig.IS_GROUP_LOG来调用此变量 buildConfigField 'boolean', 'IS_GROUP_LOG', "$IS_GROUP_LOG" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.3.2' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.2.1' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }
-
要读取的config.json文件
{"IS_GROUP_DECK": false,"IS_GROUP_PIPE": false,"IS_GROUP_EXP": false,"IS_GROUP_UI": false,"IS_GROUP_FILE": true,"IS_GROUP_LOG": true}
-
重新build项目就可以看到build任务栏打印的config.json信息
通过此方式可以很好的解决项目中针对不同客户有不同的配置的需求。我们只需要针对不同的客户定义一个配置文件即可。