简体   繁体   中英

How to read local.properties android in java files

I want to add custom fields in local.properties like

debug.username=test123
debug.password=abcd1234

can add .properties files in assets folder and read that easily.

Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
Properties properties = null;        
InputStream inputStream = assetManager.open(fileName);
properties = new Properties();
properties.load(inputStream);

But don't want to do this. As i want every team member of our to use local.properties to specify there custom attribute. which is not the part of version control system.

So how to ?

I know that this is an old question but I recently encountered the same thing and I thought I'd share my solution:

  1. Set the value in your local.properties file.
  2. Read the value in your Gradle build script and set it to a BuildConfig constant.
  3. Access the BuildConfig constant in your Java code.

local.properties

username=myUsername

build.gradle :

def getUsername() {
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    return properties.getProperty("username");
}

android {
    defaultConfig {
        buildConfigField "String", "USERNAME", "\""+getUsername()+"\""
    }
}

Example Java class:

package your.package.name;

class MyClass {
    String getUsername() {
        return BuildConfig.USERNAME; // Will return "myUsername"
    }
}
Properties properties = new Properties();
InputStream inputStream = 
this.getClass().getClassLoader().getResourceAsStream("fileName.properties");
properties.load(inputStream);
Username=properties.getProperty("username");      
password=properties.getProperty("password");

More detailed answer is here http://pillsfromtheweb.blogspot.in/2014/09/properties-file-in-android.html

and for asset use this code

        AssetManager assetManager = getAssets();
        InputStream inputStream = null;
        try {
            inputStream = assetManager.open("fileName.properties");
            properties.load(inputStream);
            String Username = properties.getProperty("username");
            String password = properties.getProperty("password");
        }
        catch (IOException e){
            Log.e("message: ",e.toString);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM