如何优雅地加载一个properties配置文件
来源:互联网 发布:黄金交易软件排名 编辑:程序博客网 时间:2024/05/01 06:56
一、前言
许多时候,系统都需要一个配置文件,重复编写这些配置文件读取程序很烦恼,又浪费时间 ,下面给一个通用的方法
二、方法论
好吧!我们用一个简单的单例模式来解决这个问题,一般来说配置文件都是加载一次就够了,最简单的单例模式(实践比空谈好)
1、私有静态对象
private static Config cfg = null;
2、构造器私有化
private Config() { properties = new Properties(); InputStream is = null; try { is = Config.class.getResourceAsStream(path); properties.load(is); } catch (Exception exception) { System.out.println("Can't read the properties file. "); } finally { try { if (is != null) { is.close(); } } catch (IOException exception) { exception.printStackTrace(); } } }
3、公有静态创建方法
public static Config getInstance() { if (cfg == null) { cfg = new Config(); } return cfg; } public static Config getInstance(String path) { path =path; if (cfg == null) { cfg = new Config(); } return cfg; }
三、代码
package common.utils;import common.log.Log;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * @author chenhaipeng * @version 1.0 * @date 2014/12/04 17:25 */public class Config { private Properties properties; private static Config cfg = null; private String path = "/config/config.properties"; private final static String ERR_MSG = "从配置文件中不能取得传入参数的返回值:"; private Config() { properties = new Properties(); InputStream is = null; try { is = Config.class.getResourceAsStream(path); properties.load(is); } catch (Exception exception) { System.out.println("Can't read the properties file. "); } finally { try { if (is != null) { is.close(); } } catch (IOException exception) { exception.printStackTrace(); } } } public static Config getInstance() { if (cfg == null) { cfg = new Config(); } return cfg; } public static Config getInstance(String path) { path =path; if (cfg == null) { cfg = new Config(); } return cfg; } /** * Retun a value for certain key. * * @param key a certain key define in properties file. * @return value */ public String getValue(String key) { if (!properties.containsKey(key)) return null; String value = properties.getProperty(key); if (value == null) { Log.getLogger().error(ERR_MSG + ":" + key); } return value; } public static void main(String args[]) { System.out.println(Config.getInstance("/config/test.properties").getValue("DB.DRIVER"));//System.out.println(Thread.currentThread().getContextClassLoader().); }}
0 0
- 如何优雅地加载一个properties配置文件
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket .
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket
- 如何优雅地关闭一个socket(转)
- Android中如何优雅地自定义一个View
- 如何"优雅"地终止一个线程?
- 如何优雅地写博客
- 如何优雅地使用NDK
- 如何优雅地使用Win10
- 如何优雅地写博客
- 学习笔记之web应用拓展
- iOS
- [codeforces] 493C
- C语言学习入门 (八) 结构体和枚举
- HDU 1213 How Many Tables (并查集)
- 如何优雅地加载一个properties配置文件
- Java中二进制字节数组与十六进制互转
- [转载]error:jump to case label
- getline()函数的几点疑惑
- 计算机科学中最重要的32个算法
- Resource Type总结
- 黑马程序员——java基础之薄弱点总结(六)
- Maven实战(一)安装与配置
- 多线程程序中操作的原子性