如何读取app文件夹下的配置文件

How to read a config file which is under app folder

我在应用程序文件夹中有一个配置文件 config.properties。我在 build.gradle 中将其用于构建配置。 我需要在 java 代码中阅读此文件。但是我可以弄清楚我应该使用 path 。我如何在 java 代码中读取此文件。下面的代码给我 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();
    }

我在 build.gradle 中使用相同的文件并且它工作正常。如下 .

 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 部分工作正常,我可以分配属性。但是我需要在 java class 中读取同一个文件。我应该为 File.

使用什么路径

配置文件如下所示:

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

理想情况下,您应该将特定于应用程序的文件放在资产文件夹下,并将 gradle 构建配置和特定于应用程序的配置分开。在 assets/configs 文件夹下添加特定于应用程序的配置属性文件。那么你可以这样阅读:

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

如果您仍想继续,那么唯一的方法是将文件放在资产文件夹中,然后在您的 build.gradle 中使用

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

好的,让我们回到基础。首先,您在 build.gradle 中创建属性,然后使用自定义字段创建 buildConfigField

productFlavors {
    play {
        dimension "MyDimension"

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

        //...

        buildConfigField "int", "MY_VERSION_CODE", "$properties_versionCode"
        buildConfigField "String", "MY_VERSION_NAME", "\"$properties_versionName\""

    }
}

重建项目后,字段将能够从BuildConfig.{FIELD}调用。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //...

    Log.d(TAG, "Version Name: " + BuildConfig.MY_VERSION_NAME);
    Log.d(TAG, "Version Code: " + BuildConfig.MY_VERSION_CODE);

    //...
}

更多信息here