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

一: 理解根目录

<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路径)进行查找。

二:this.getClass().getResourceAsStream和this.getClass().getClassLoader().getResourceAsStream的区别

 (1)关于getClass().getClassLoader()

InputStream is  = this.getClass().getClassLoader().getResourceAsStream("helloworld.properties");

其中this.getClass()和getClassLoader()都是什么意思呀.?

 getClass():取得当前对象所属的Class对象   
 getClassLoader():取得该Class对象的类装载器

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/h2604396739/article/details/83860334

猜你喜欢

转载自www.cnblogs.com/myseries/p/10572449.html
今日推荐