如何读取应用程序文件夹下的配置文件 [英] How to read a config file which is under app folder

查看:271
本文介绍了如何读取应用程序文件夹下的配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在app文件夹中有一个配置文件config.properties.我正在使用哪个在build.gradle中进行构建配置. 我需要用Java代码读取此文件.但是我可以弄清楚我应该使用path.我如何用Java代码读取此文件.下面的代码给了我FileNotFoundException

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();
    }

我在build.gradle中使用了相同的文件,并且运行良好.如下.

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部分工作正常,我能够分配属性.但是我需要在java类中读取相同的文件. File应该使用什么路径.

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.

配置文件如下:

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

推荐答案

理想情况下,应将特定于应用程序的文件放在Assets文件夹下,并将gradle构建配置和特定于应用程序的配置分开.在assets/configs文件夹下添加应用程序特定的配置属性文件.然后,您可以阅读如下内容:

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);

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

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')))

这篇关于如何读取应用程序文件夹下的配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆