class.getResourceAsStream 用法
首先,Java中的getResourceAsStream有以下几种 Class.getResourceAsStream(String path) : path 不以’/‘开头时默认是从此类所在的包下取资源,以’/‘开头则是从
ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
2. Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/‘开头,最终是由
ClassLoader获取资源。
3. ServletContext. getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/‘开头无所谓,
当然这和具体的容器实现有关。
4. Jsp下的application内置对象就是上面的ServletContext的一种实现。
其次,getResourceAsStream 用法大致有以下几种
第一: 要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类me.class ,同时有资源文件myfile.xml
那么,应该有如下代码
me.class.getResourceAsStream("myfile.xml");
第二:在me.class目录的子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.y.file 目录下有资源文件myfile.xml
那么,应该有如下代码
me.class.getResourceAsStream("file/myfile.xml");
第三:不在me.class目录下,也不在子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.file 目录下有资源文件myfile.xml
那么,应该有如下代码
me.class.getResourceAsStream("/com/x/file/myfile.xml");
总结一下,可能只是两种写法
第一:前面有 “ / ”
“ / ”代表了工程的根目录,例如工程名叫做myproject,“ / ”代表了myproject
me.class.getResourceAsStream("/com/x/file/myfile.xml");
第二:前面没有 “ / ”
代表当前类的目录
me.class.getResourceAsStream("myfile.xml");
me.class.getResourceAsStream("file/myfile.xml");
src(源文件夹)
┃
┣━11.properties
┃
┗━myspider(myspider包)
┃
┣━22.properties
┗━Test.java
package myspider;
import java.io.UnsupportedEncodingException;
/**
*
* @author mark
*/
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException{
Test t=new Test();
//文件名前不加“/”,则表示从当前类所在的包下查找该资源。如下则表示的是从包myspider下查找22.properties文件资源。
System.out.println("1:"+t.getClass().getResourceAsStream("22.properties"));//输出[email protected]
//文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找22.properties文件资源。
System.out.println("2:"+t.getClass().getResourceAsStream("/22.properties"));//输出null
//文件名前加了“/”,则表示从类路径下也就是从classes文件夹下查找资源,如下表示从classes文件夹下查找11.properties文件资源。
System.out.println("3:"+t.getClass().getResourceAsStream("/11.properties"));//输出[email protected]
System.out.println();
//当前包路径4:file:/E:/myobject/myspider/build/classes/myspider/
System.out.println("4:"+t.getClass().getResource(""));
//输出当前类路径5:file:/E:/myobject/myspider/build/classes/
System.out.println("5:"+t.getClass().getResource("/"));
/*
* 如果类路径下的当前包有22.properties文件,则输出6:file:/E:/myobject/myspider/build/classes/myspider/22.properties
* 否者输出源文件下的22.properties文件的路径,则输出:6:file:/E:/myobject/myspider/src/myspider/22.properties
*/
System.out.println("6:"+t.getClass().getResource("22.properties"));
/*
* 如果类路径下有11.properties文件,则输出7:file:/E:/myobject/myspider/build/classes/11.properties
* 否者输出源文件下的11.properties文件的路径,则输出:6:7:file:/E:/myobject/myspider/src/11.properties
*/
System.out.println("7:"+t.getClass().getResource("/11.properties"));
}
}