读取项目属性文件的几种方式

47 阅读1分钟

项目中会把一些环境变量、公共属性配置到属性文件中,总结了一些工程加载属性文件的方式。

直接读取

    private Set<Map.Entry<Object, Object>> loadPropertyFile(String pathName) {
        Set<Map.Entry<Object, Object>> set = new HashSet<>();
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(pathName);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            Properties properties = new Properties();
            properties.load(inputStreamReader);
            set = properties.entrySet();
        } catch (IOException e) {
            System.out.println("load local property file failed");
            e.printStackTrace();
        }
        return set;
    }

使用ResourceBundle

		//参数文件名
		private static String SYSPARAM_FILE = "application";
		
		private static ResourceBundle BUNDLE = ResourceBundle.getBundle(SYSPARAM_FILE);
		
		//读取配置参数
		public static String getParam(String key){
			return BUNDLE.getString(key);
		}