Search code examples
androidgradleandroid-file

How to read a config file which is under app folder


I am having a config fie config.properties inside app folder . Which i am using for build configurations in build.gradle. I need to read this file in java code . But i can figure out the path should i use . How can i read this file in java code . code below gives me FileNotFoundException

 try {
        Properties properties = new Properties();
        File inputStream=new File("/config.properties");
        properties.load(new FileInputStream(inputStream));
        return properties.getProperty("BASE_URL");
    }catch (IOException e){
        e.printStackTrace();
    }

I am using the same file in build.gradle and its working well . as below .

 defaultConfig {
    Properties versionProps = new Properties()
    versionProps.load(new FileInputStream(file('config.properties')))
    def properties_versionCode = versionProps['VERSION_CODE'].toInteger()
    def properties_versionName = versionProps['VERSION_NAME']
    def properties_appid= versionProps['APPLICATION_ID']


    applicationId properties_appid
    minSdkVersion 14
    targetSdkVersion 26
    versionCode properties_versionCode
    versionName properties_versionName
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

build.gradle part is working fine and i am able to assign properties . But i need to read the same file in a java class . What path should i use for File.

Config file looks like:

VERSION_NAME=1.0.0
VERSION_CODE=1
APPLICATION_ID=com.app.drecula
BASE_URL=https://reqres.in/

Solution

  • Ideally you should put application specific file under assets folder and separate your gradle build configuration and application specific configuration. Add application specific configuration properties file under assets/configs folder. Then you can read it as follows:

      final Properties properties = new Properties();
      final AssetManager assetManager = getAssets();
      final InputStream inputStream= assetManager.open("configs/config.properties");
      properties.load(inputStream);
    

    If you still want to proceed, then only way would be to put the file in assets folder and in your build.gradle use

    versionProps.load(new FileInputStream(file('/src/main/assets/config/config.properties')))