您的位置:首页 > 其它

正确使用Class.getResourceAsStream("")与Class.getClassLoader().getResourceAsStream("")

2015-05-28 13:12 561 查看


方法getResourceAsStream("")与getResource("")均常被用于获取编译路径下指定的配置文件,用法相似,下面以getResource("")为例展示其正确用法:

/**
* 无package
*/
System.out.println(this.getClass().getResource("template.xml").getPath());//相对当前Class路径下的template.xml
System.out.println(this.getClass().getResource("/template.xml").getPath());//classpath根路径下的template.xml
System.out.println(this.getClass().getClassLoader().getResource("template.xml").getPath());//classpath根路径下的template.xml
/**
* package
*/
System.out.println(this.getClass().getResource("package/template.xml").getPath());//相对当前Class路径/package路径下的template.xml
System.out.println(this.getClass().getResource("/package/template.xml").getPath());//classpath根路径/package路径下的template.xml
System.out.println(this.getClass().getClassLoader().getResource("package/template.xml").getPath());//classpath根路径/package路径下的template.xml

错误用法(注意斜杠):

/**
* 无package
*/
System.out.println(this.getClass().getClassLoader().getResource("/template.xml").getPath());//classpath根路径下的template.xml
/**
* package
*/
System.out.println(this.getClass().getClassLoader().getResource("/package/template.xml").getPath());//classpath根路径/package路径下的template.xml

注意:在Jar包中获取配置文件时,建议通过getResourceAsStream("")的方式编码。

JAVA基础普及:

Classloader 类加载器,用来加载 Java 类到 Java 虚拟机中。与普通程序不同的是。Java程序(class文件)并不是本地的可执行程序。当运行Java程序时,首先运行JVM(Java虚拟机),然后再把Java class加载到JVM里头运行,负责加载Java class的这部分就叫做Class Loader。

JVM本身包含了一个ClassLoader称为Bootstrap ClassLoader,和JVM一样,BootstrapClassLoader是用本地代码实现的,它负责加载核心JavaClass(即所有java.*开头的类)。另外JVM还会提供两个ClassLoader,它们都是用Java语言编写的,由BootstrapClassLoader加载;其中Extension ClassLoader负责加载扩展的Javaclass(例如所有javax.*开头的类和存放在JRE的ext目录下的类),ApplicationClassLoader负责加载应用程序自身的类。

当运行一个程序的时候,JVM启动,运行bootstrapclassloader,该ClassLoader加载java核心API(ExtClassLoader和AppClassLoader也在此时被加载),然后调用ExtClassLoader加载扩展API,最后AppClassLoader加载CLASSPATH目录下定义的Class,这就是一个程序最基本的加载流程。

Best Wishes For You!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐