java读取.properties配置文件的几种方法

转载:原文地址 http://www.cnblogs.com/s3189454231s/p/5626557.html

读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):

一.通过jdk提供的java.util.Properties类

    此类继承自java.util.HashTable,即实现了Map接口,所以,可使用相应的方法来操作属性文件,但不建议使用像put、putAll这 两个方法,因为put方法不仅允许存入String类型的value,还可以存入Object类型的。因此java.util.Properties类提 供了getProperty()和setProperty()方法来操作属性文件,同时使用store或save(已过时)来保存属性值(把属性值写 入.properties配置文件)。在使用之前,还需要加载属性文件,它提供了两个方法:load和loadFromXML。

    load有两个方法的重载:load(InputStream inStream)、load(Reader reader),所以,可根据不同的方式来加载属性文件。

    可根据不同的方式来获取InputStream,如:

1.通过当前类加载器的getResourceAsStream方法获取下载地址

InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("test.properties");  

2.从文件获取

InputStream inStream = new FileInputStream(new File("filePath"));  

3.也是通过类加载器来获取,和第一种一样

InputStream in = ClassLoader.getSystemResourceAsStream("filePath");  

4.在servlet中,还可以通过context来获取InputStream

InputStream in = context.getResourceAsStream("filePath");  

5.通过URL来获取

URL url = new URL("path");  
InputStream inStream = url.openStream();  

读取方法如下:

Properties prop = new Properties();    
prop.load(inStream);    
String key = prop.getProperty("username");    
//String key = (String) prop.get("username");  

二.通过java.util.ResourceBundle类读取

    这种方式比使用Properties要方便一些。

1.通过ResourceBundle.getBundle()静态方法来获取

    ResourceBundle是一个抽象类,这种方式来获取properties属性文件不需要加.properties后缀名,只需要文件名即可。
ResourceBundle resource = ResourceBundle.getBundle("com/mmq/test");//test为属性文件名,放在包com.mmq下,如果是放在src下,直接用test即可    
String key = resource.getString("username");  

2.从InputStream中读取

    获取InputStream的方法和上面一样,不再赘述。
ResourceBundle resource = new PropertyResourceBundle(inStream);  
    注意:在使用中遇到的最大的问题可能是配置文件的路径问题,如果配置文件入在当前类所在的包下,那么需要使用包名限定, 如:test.properties入在com.mmq包下,则要使用com/mmq/test.properties(通过Properties来获 取)或com/mmq/test(通过ResourceBundle来获取);属性文件在src根目录下,则直接使用test.properties 下载地址   或test即可。

三.实例

ResourceLoader.java

package com.bijian.study;  

import java.io.File;  
import java.io.FileInputStream;  
import java.util.HashMap;  
import java.util.Map;  
import java.util.Properties;  

public final class ResourceLoader {  

    private static ResourceLoader loader = new ResourceLoader();  
    private static Map<String, Properties> loaderMap = new HashMap<String, Properties>();  

    private ResourceLoader() {  
    }  

    public static ResourceLoader getInstance() {  
        return loader;  
    }  

    public Properties getPropFromProperties(String fileName) throws Exception {  

        Properties prop = loaderMap.get(fileName);  
        if (prop != null) {  
            return prop;  
        }  
        String filePath = null;  
        String configPath = System.getProperty("configurePath");  

        if (configPath == null) {  
            filePath = this.getClass().getClassLoader().getResource(fileName).getPath();  
        } else {  
            filePath = configPath + "/" + fileName;  
        }  
        prop = new Properties();  
        prop.load(new FileInputStream(new File(filePath)));  

        loaderMap.put(fileName, prop);  
        return prop;  
    }  
}  

PropertiesUtil.java

package com.bijian.study;  

import java.util.Properties;  
import java.util.concurrent.ConcurrentHashMap;  
import java.util.concurrent.ConcurrentMap;  

/** 
 * 用ConcurrentMap来缓存属性文件的key-value 
 */  
public class PropertiesUtil {  

    private static ResourceLoader loader = ResourceLoader.getInstance();  
    private static ConcurrentMap<String, String> configMap = new ConcurrentHashMap<String, String>();  
    private static final String DEFAULT_CONFIG_FILE = "test.properties";  

    private static Properties prop = null;  

    public static String getStringByKey(String key, String propName) {  
        try {  
            prop = loader.getPropFromProperties(propName);  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }  
        key = key.trim();  
        if (!configMap.containsKey(key)) {  
            if (prop.getProperty(key) != null) {  
                configMap.put(key, prop.getProperty(key));  
            }  
        }  
        return configMap.get(key);  
    }  

    public static String getStringByKey(String key) {  
        return getStringByKey(key, DEFAULT_CONFIG_FILE);  
    }  

    public static Properties getProperties() {  
        try {  
            return loader.getPropFromProperties(DEFAULT_CONFIG_FILE);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
} 

Constant.java

package com.bijian.study;  

public class Constant {  

    public static final String TEST = PropertiesUtil.getStringByKey("test", "test.properties");  
}  

Main.java

package com.bijian.study;  

public class Main {  

    public static void main(String[] args) {  

        System.out.println(Constant.TEST);  
    }  
}  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值