理解根目录,getClass().getResourceAsStream和getClass().getClassLoader().getResourceAsStream的区别

版权声明:转载请注明出处 https://blog.csdn.net/h2604396739/article/details/83860334

1理解根目录:


经常会看到如下配置:

<value>classpath*:/application.properties</value> 
<value>classpath:/application.properties</value>

这里的classpath怎么理解呢,其实指的就是根目录,关于根目录,需要了解:

1、src不是classpath, WEB-INF/classes,lib才是classpath,WEB-INF/ 是资源目录, 客户端不能直接访问。

2、WEB-INF/classes目录存放src目录java文件编译之后的class文件、xml、properties等资源配置文件,这是一个定位资源的入口。

3、引用classpath路径下的文件,只需在文件名前加classpath:

<param-value>classpath:applicationContext-*.xml</param-value> 
<!-- 引用其子目录下的文件,如 -->
<param-value>classpath:context/conf/controller.xml</param-value>

4、lib和classes同属classpath,两者的访问优先级为: lib>classes。

5、classpath 和 classpath* 区别:

classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找。


2getClass().getResourceAsStream和getClass().getClassLoader().getResourceAsStream的区别

文件结构如下图:

途中有两个配置文件,biabc.properties和abc.properties;Test类读取方式如下:

  public void readProperty(){
        //从当前类所在包下加载指定名称的文件,getClass是到当前列
        InputStream in = this.getClass().getResourceAsStream("biabc.properties");
        // 从classpath根目录下加载指定名称的文件,这是因为/即代表根目录
//        InputStream in = this.getClass().getResourceAsStream("/abc.properties");
        //从classpath根目录下加载指定名称的文件,这是因为getClassLoader就会到根目录上
//        InputStream in = this.getClass().getClassLoader().getResourceAsStream("abc.properties");

        Properties properties = new Properties();
        // 使用properties对象加载输入流
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取key对应的value值
        System.out.println(properties.getProperty( "a"));
    }

借鉴;https://blog.csdn.net/javaloveiphone/article/details/51994268

猜你喜欢

转载自blog.csdn.net/h2604396739/article/details/83860334
今日推荐