Java中getResourceAsStream的用法

//constant.properties文件目录 /webapp/WEB-INF/classes/constant.properties
Properties pro = new Properties();// 属性集合对象
// 将属性文件流装载Properties对象中
pro.load(Constant.class.getClassLoader().getResourceAsStream("constant.properties"));
time = Integer.parseInt(pro.getProperty("time")) ;//获取文件中的属性time
   或是
        Properties prop = new Properties();  
  
        //得到的是编译后的bin的目录Class.class.getClass().getResource("/").getPath();  
          
        //这个是绝对路径  
//      String filepath = "E:\\myeclipse6\\workspace\\XXX\\src\\testproperties\\constants.properties";  
          
        String filepath = Class.class.getClass().getResource("/").getPath()+"/testproperties/constants.properties" ;  
        
        System.out.println("++++++++++++"+Class.class.getClass().getResource("/").getPath()+"+++++++++++++");  
          
        FileInputStream fis = null;  
        try {  
          fis = new FileInputStream(filepath);  
          prop.load(fis);  
          Constants.userName = prop.getProperty("userName");  
          Constants.age = Integer.parseInt(prop.getProperty("age"));  
          Constants.password = prop.getProperty("password");  
          System.out.println(Constants.userName+Constants.age+Constants.password);;  
          System.out.println("#############################加载配置信息完成###########################");  
        }  
        catch (IOException e) {  
          System.out.println("加载constants.properties文件失败,文件不存在后者路径不正确! ");  
          e.printStackTrace();  
        }  
      }

首先,Java中的getResourceAsStream有以下几种: 
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是否以’/'开头无所谓,

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

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");


你可能感兴趣的:(Java中getResourceAsStream的用法)