11

I defined a property in gradle.properties file like below:

user.password=mypassword

Can I use it as a variable value in my java statement?

Opal
  • 81,889
  • 28
  • 189
  • 210
Desmond Yao
  • 545
  • 1
  • 4
  • 10

2 Answers2

11

Yes you can, however this is not a good idea nor a good practice. gradle.properties file is meant to keep gradle's properties itself, e.g. JVM args used at build time.

If you need to store user/pass pair in properties file, it should be placed under src/main/resources or other appropriate folder and separate from gradle.properties.

Side note: Not sure if keeping properties file in mobile application is safe in general.

Opal
  • 81,889
  • 28
  • 189
  • 210
  • 1
    Thank you:) I'll be care of it! – Desmond Yao Jul 29 '15 at 04:25
  • but my Config file need to store access key id and secret key. Where Config.Java have only string and integers to fetech the values through the app, but access key id and secretkey have use in Config file to create Authenticate Object. I have warning from Google Play Developer Console as it open to view, it may misuse. – Prasad Dec 06 '17 at 13:27
  • 4
    WRONG! Private keys, passwords and personal data MUST be in gradle.properties – Demetrio Guilardi Oct 28 '18 at 04:49
  • 2
    If user/pass is present in resources, it needs to be shipped to customers. Ideally, they should be in `gradle.properties` only which is not shipped. If someone wants to use it, they would need to add the required user/pass in their own `gradle.properties`. AFAIK, that is the right approach – Rakesh N Sep 17 '19 at 11:37
9

You would have to read the properties file and extract the property first.

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("gradle.properties");

    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("user.password"));
} catch (IOException ex) {
    ex.printStackTrace();
}

You can find the detailed tutorial here

Padawan
  • 370
  • 1
  • 10
  • 6
    Wouldn't the gradle.properties file cease to exist in a compiled application? – Abandoned Cart Jul 17 '21 at 14:15
  • @AbandonedCart yes, it would. No popular resource packager takes the build script files and bundles them with the output. This might work temporarily, if the output executable is in the project's root directory next to gradle.properties, but as soon as you move the executable out (which you will inevitably do), the properties file will not be accessible anymore. – milosmns Jun 17 '23 at 14:23
  • @milosmns It seems I was mistakenly tagged, but not the intended audience. It's also not possible to edit comments after the first 5 minutes. – Abandoned Cart Jun 18 '23 at 15:36