Create a properties file using gradle

I would like to create a properties file called "dev.properties" using gradle. Here is my build.gradle code:

buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.8.+' } } apply plugin: 'android' repositories { mavenCentral() } android { compileSdkVersion 16 buildToolsVersion "19.0.0" defaultConfig { minSdkVersion 16 targetSdkVersion 16 } def prop = new Properties() def propFile = new File("dev.properties"); propFile.createNewFile(); prop.store(propFile.newWriter(), null); buildTypes { release { runProguard false proguardFile getDefaultProguardFile('proguard-android.txt') } } } 

The file is created when I right-click on build.gradle and select run. However, it is not created when I do the whole project. Why?

I am using android studio 0.4.6 with gradle 1.10.

+7
android android-studio gradle
source share
1 answer

It creates the file, not where you expect it to be. Your script creates a file inside the current working directory and in Android Studio, which will be located in the Android Studio distribution. There was an error that made Android Studio match the command line ( https://code.google.com/p/android/issues/detail?id=65552 ) and placed the working directory in the root directory of the project (well, suppose your working the directory is there when you issue the Gradle commands), but the fix is ​​actually difficult, and the real answer is that you probably should never implicitly rely on the working directory so that you can make your assemblies as bulletproof as possible.

If you do something like this:

 def propFile = new File("${project.rootDir}/dev.properties") 

it will put the file in the root directory of the project. There is also project.projectDir , which will be your module directory; see http://www.gradle.org/docs/current/dsl/org.gradle.api.Project.html for more information on what is available to you.

As a note, keep in mind that this will be executed every time the build file is evaluated (since the android block is executed every time the script is built), which may be more often than you want. It is more than just building time; This is the time of importing the project, as well as at any time when Android Studio decides to evaluate the build file that occurs when the project is opened, as well as when you click the Synchronize project button using the Gradle Files button .

In addition, you should consider at what stage in the build process you want this to happen: is this the evaluation time script, or do you want it to start after Gradle has completed his analysis and is ready to actually start building things? You can read http://www.gradle.org/docs/current/userguide/build_lifecycle.html to learn more about this.

Sorry, I know that you need a lot of information when you are just trying to do something, but these concepts will help you pretty soon along the way.

+11
source share

All Articles