【Java】properties文件存放位置与加载方式

【前言】经常使用Properties文件存放配置,当运行代码Properties properties = new Properties; properties.load(fileStream);的时候,是不是经常会遇到文件不存在的提示?在尝试了多种方法后,终于找到了如何正确地加载properties文件。

【放置位置】

Properties文件放在src目录下,工程编译完成的时候会自动将这个.properties文件复制到class目录下,这就是所谓的“把properties”放在class目录下,完全不需要去找class目录,只要放在src目录即可。我的properties文件就叫做tag.properties,它放在src目录下。

【如何加载】

  • 方法一

假如我在PlayGround类的一个static方法中加载Properties的代码如下:

Properties properties = new Properties();

properties.load(PlayGround.class.getClassLoader().getResourceAsStream("tag.properties"));


假如我是在非static方法中加载Properties,代码如下:

Properties properties = new Properties();

properties.load(this.getClass().getClassLoader().getResourceAsStream("tag.properties"));

区别是static方法中,要用 类名.class,非static方法中用this.getClass()即可。原理都是找到类加载器的位置,这个位置的默认值即class目录。

  • 方法二

继续以非static方法中加载为例(用了j 1.7 的条件try...catch。1.6继续用finally方式清除iStream)

        Properties properties = new Properties();
        try (InputStream iStream = new FileInputStream(this.getClass().getResource("/").getPath()+"tag.properties");){    
            properties.load(iStream);
            System.out.println(properties.getProperty("defaultDBName"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


方法二的思路不再是类加载器的路径,而是.class文件资源存放的位置。getResource("/").getPath()就是Class目录,再加上properties文件名就可以加载了。不过这种方法稍稍有点瑕疵,在Windows下,这段代码

this.getClass().getResource("/").getPath()+"tag.properties"

返回的路径是以 /E:/... 的形式出现的,即前面有个斜杠'/'。有时候这个东西会让工程死活加载不了文件。


【web工程中的问题】

针对web工程,有推荐把Properties文件放在WEB-INF目录下的,有推荐放WebContent目录下的,个人并不推荐这么做。

如果是给servlet用,可以用web.xml来配置。并且我认为servlet中应该干干净净才好,它就做控制器来组织流程,至于逻辑实现放在各种插件类上:这样符合MVC的思路。如果不是给servlet用,放在src目录下更合理。


  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值