java中getResourceAsStream(String path)与getClassLoader.getResourceAsStream(String path)

1. 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是否以’/'开头无所谓,

当然这和具体的容器实现有关。

例子:

|---路径问题

      |--bin

         |--path(包)

                  |--PathTest.class

                  |--name.txt (内容:my name is xiaoming!)

         |--address.txt   (内容:I live in wuhan!)

      |--src

         |--path(包)

                      |--PathTest.java

                      |--read.txt (内容:I like java book!)

         |--dream.txt  (内容:I have a dream!)



package path;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


public class PathTest {


public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
PathTest t=new PathTest();
//InputStream in = t.getClass().getResourceAsStream("/path/name.txt");
InputStream in = t.getClass().getResourceAsStream("name.txt");
byte[] buffer=new byte[1024];
int len = in.read(buffer);
//my name is xiaoming !
System.out.println(new String(buffer,0,len));
//file:/D:/workspace/路径问题/bin/path/
System.out.println(t.getClass().getResource(""));

in = t.getClass().getClassLoader().getResourceAsStream("address.txt");
len = in.read(buffer);
//i live in wuhan !
System.out.println(new String(buffer,0,len));
//file:/D:/workspace/路径问题/bin/
System.out.println(t.getClass().getClassLoader().getResource(""));

in = t.getClass().getResourceAsStream("/address.txt");
len = in.read(buffer);
//i live in wuhan !
System.out.println(new String(buffer,0,len));

System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径 
//D:\workspace\路径问题
in = new FileInputStream("src/dream.txt");
len = in.read(buffer);
System.out.println(new String(buffer,0,len));
// i have a dream!!

}

}
 


你可能感兴趣的:(java中getResourceAsStream(String path)与getClassLoader.getResourceAsStream(String path))