简单读properties文件的例子

读取classpath下的properties文件并存到字典中

public void contextInitialized(ServletContextEvent servletContextEvent) {
        InputStream in = getClass().getClassLoader().getResourceAsStream("/upload.properties");

        Properties properties = new Properties();
        try {
            properties.load(in);

            for(Map.Entry<Object,Object > prop: properties.entrySet())
            {
                String propertyName = (String) prop.getKey();
                String propertyValue = (String) prop.getValue();
                FileUploadProperties.getInstance().addProperty(propertyName,propertyValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
其中
getClass().getClassLoader().getResourceAsStream("/upload.properties");
getClass().getResourceAsStream("/upload.properties");
的区别如下:

Class.getResourceAsStream() 会指定要加载的资源路径与当前类所在包的路径一致。

     例如你写了一个MyTest类在包com.test.mycode 下,那么MyTest.class.getResourceAsStream("name") 会在com.test.mycode包下查找相应的资源。

     如果这个name是以 '/' 开头的,那么就会从classpath的根路径下开始查找。

  

    ClassLoader.getResourceAsStream()  无论要查找的资源前面是否带'/' 都会从classpath的根路径下查找。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值