首页 > 系统 > Android > 正文

Java语言读取配置文件config.properties的方法讲解

2019-12-12 00:15:13
字体:
来源:转载
供稿:网友

应用场景

有些时候项目中会用到很多路径,并且很可能多个路径在同一个根目录下,那为了方便配置的修改,达到只修改根目录即可达到一改全改的效果,此时就会想到要是有变量就好了;

另外有时候路径中的文件名是不确定的,要靠业务程序运行时去判断文件名应该如何设置,而又希望此文件下的目录名是确定的,那此时用变量也是比较好的解决方式。

一、配置文件config.properties是放在src根目录下的:例如我的是 /PropertiesTest/src/com/xuliugen/project/type.properties

配置文件中的内容如下:

left=com.sunny.project.LeftHairright=com.sunny.project.RightHairin=com.sunny.project.InHair

读取配置文件中的代码如下:

public class PropertiesReader {  public static void main(String[] args) {    new PropertiesReader().getProperties();  }  public Map<String, String> getProperties() {    Properties props = new Properties();    Map<String, String> map = new HashMap<String, String>();    try {      InputStream in = getClass().getResourceAsStream("type.properties");      props.load(in);      Enumeration en = props.propertyNames();      while (en.hasMoreElements()) {        String key = (String) en.nextElement();        String property = props.getProperty(key);        map.put(key, property);        System.out.println(key + " " + property);      }    } catch (Exception e) {      e.printStackTrace();    }    return map;  }}

运行结果如下:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对武林网的支持。如果你想了解更多相关内容请查看下面相关链接

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表