两种方式读取properties配置文件

在Java中我们经常会将我们自定义的配置文件xxx.properties,读取到我们的Java代码中去。现在我目前已知有两种读取配置文件的方式,如下所示。

方式一:使用Properties集合工具类读取配置文件。

Properties的加载方法:

方法名 说明
void load(Reader reader) 从输入字符流读取属性列表(键和元素对)
void  store(Writer  writer,  String  comments) 将此属性列表(键和元素对)写入此Properties表中,一适合使用load(Reader)方法的格式写入输出字符流

加载完成后根据下面方法获取值

方法名 说明
Object  setProperty(String  key,String  value) 设置集合的键和值,都是String类型,底层调用 Hashtable方法put
String  getProperty(String  key) 使用此属性列表中指定的键搜索属性
Set  stringPropertyNames() 从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串。

代码演示:

// properties文件略

        Properties pro = new Properties();
        int maxTotal = 0;
        int maxIdel = 0;
        String host = null;
        int port = 0;
        try {
            pro.load(new FileReader("D:\\360驱动大师目录\\Redis\\Jedis_Test\\src\\redis.properties"));
            maxTotal = Integer.parseInt(pro.getProperty("redis.maxTotal"));
            maxIdel = Integer.parseInt(pro.getProperty("redis.maxIdel"));
            host = pro.getProperty("redis.host");
            port = Integer.parseInt(pro.getProperty("redis.port"));
        } catch (IOException e) {
            e.printStackTrace();
        }

方式二:使用ResourceBundle工具类读取配置文件

ResourceBoundle加载方法

返回类型 方法名 描述
static  ResourceBundle getBundle(String  basename) 使用指定的基本名称,默认语言环境和调用者的类加载器获取资源包

加载完成后根据下面方法获取值

返回类型 方法名 描述
Object getObject(String  key) 从此资源包根据键获取值,将值以Object类型返回
String getString(String  key) 从此资源包根据键获取值,将值以String类型返回
String[] getStringArray(String  key) 从此资源包根据键获取值,将值以列表类型返回

代码演示:

ResourceBundle bundle = ResourceBundle.getBundle("redis");
int maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));
int maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel"));
String host = bundle.getString("redis.host");
int port = Integer.parseInt(bundle.getString("redis.port"));

你可能感兴趣的:(Java,java,jar,服务器)