Android 读写配置文件properties

    技术2022-07-14  80

    1、首先在源代码根目录(src下)下创建一个名为global.properties的文件(也可以在其他目录下)。或者在assets文件夹下创建一个名为global.properties的文件。

    2、打开global.properties文件,在该文件中添加下列代码

    #后台接口url url=http://121.15.209.220 #端口号 port=8080

    说明:上面代码中,#为配置文件中的注释,而在配置文件中,可以使用<br>等进行格式处理,在配置文件中,如果某个属性过长,一行不能输入完全是,可以通过 通知系统,下一行同样为该属性的值。

    3、创建一个工具类

    /** * 配置文件读取 */ public class PropertiesUtils { //1、配置文件的位置在assets资源目录下 private final static String m_strPath = "/assets/global.properties"; //2、配置文件的位置在源代码根目录(src下) //private final static String m_strPath = "/global.properties"; public static Properties getProperties(Context c){ Properties props = new Properties(); try { //方法一:通过activity中的context获取setting.properties的FileInputStream //注意这地方的参数appConfig在eclipse中应该是appConfig.properties才对,但在studio中不用写后缀 //InputStream in = c.getAssets().open("appConfig.properties"); //InputStream in = c.getAssets().open("appConfig"); //方法二:通过class获取setting.properties的FileInputStream InputStream in = PropertiesUtils.class.getResourceAsStream(m_strPath); props.load(in); } catch (Exception e) { e.printStackTrace(); } return props; } /** * 使用样例 */ private void example(){ //String url = PropertiesUtils.getProperties(getApplicationContext()).getProperty("url"); String url = PropertiesUtils.getProperties(null).getProperty("url"); } }

    4.在需要使用配置文件中配置的属性值时,直接调用上述方法即可,如下所示。

    String url = PropertiesUtils.getProperties(null).getProperty("url");

    完!!!

    Processed: 0.022, SQL: 9