在java代码中一次性读取.properties文件的内容及.properties文件路径相关问题

1.一次性读取.properties文件的内容

Properties本身就是个Hashtable,可以像HashMap那样遍历出来。

1)配置文件config.properties与ProperUtil类、Test类放在同级,里面的内容如:

username=zhangsan

password=123

2)读取文件的方法类:

public class ProperUtil {

private static final String fileName = "config.properties";
    private static Properties proper = new Properties();
    static{
        try {
            proper.load(ProperUtil.class.getResourceAsStream(fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static Map<String, String> getAllProperties(){
        Map<String, String> map = new HashMap<String, String>();
        Enumeration en = proper.propertyNames();
        String key  = "";
        String value = "";
        while(en.hasMoreElements()){
            key = (String)en.nextElement();
            value = proper.getProperty(key);
            map.put(key, value);
        }
        return map;
    }

}

3)测试方法类:

public class Test {

public static void main(String[] args) {
Map<String,String> map=ProperUtil.getAllProperties();
System.out.println(map.size());
System.out.println(map.get("username"));
System.out.println(map.get("password"));

}

}

经过测试能够读出文件中的username与password


2..properties文件路径相关问题


                                                        

图上的src/main/java,src/main/resources-dev,src/main/resources,src/test/java这几个文件下的一级目录都是放在web应用程序的根目录(‘/’Web应用程序的根目录的绝对路径

解释:用下面的方式读取system.config.properties文件

    String fileName = "config.properties";

    Properties proper = new Properties();

   proper.load(ProperUtil.class.getResourceAsStream(fileName));

应该写String fileName = "/system.config.properties";

当这个配置文件在com/下

应该写为String fileName = "/com/system.config.properties";



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值