java获得文件目录

获得class或项目的内文件目录有多种种方式,
  第一种,用Class.getResourceAsStream(String str);
          等同于ClassLoader.getResourceAsStream(String str);
          srt 的等于 null,
        在web项目,和非jar项目想运行时,
              str == null时
            web项目    ClassLoader.getResourceAsStream 等于class根目录
           
       查找具有给定名称的资源。查找与给定类相关的资源的规则是通过定义类的 class loader 实现的。此方法委托此对象的类加载器。如果此对象通过引导类加载器加载,则此方法将委托给 ClassLoader.getSystemResourceAsStream(java.lang.String)。


class与classLoader的 getResource对比。
System.out.println(SimpleMinaServer.class.getResource(""));
System.out.println(SimpleMinaServer.class.getResource("."));
System.out.println(SimpleMinaServer.class.getResource("/"));
System.out.println(SimpleMinaServer.class.getClassLoader().getResource(""));
System.out.println(SimpleMinaServer.class.getClassLoader().getResource("."));
System.out.println(SimpleMinaServer.class.getClassLoader().getResource("/"));

file:/G:/Work%20space/My%20Work%20space/j2ee/c5s_im(20130205)/bin/mima/service/
file:/G:/Work%20space/My%20Work%20space/j2ee/c5s_im(20130205)/bin/mima/service/
file:/G:/Work%20space/My%20Work%20space/j2ee/c5s_im(20130205)/bin/
file:/G:/Work%20space/My%20Work%20space/j2ee/c5s_im(20130205)/bin/
file:/G:/Work%20space/My%20Work%20space/j2ee/c5s_im(20130205)/bin/
null

总结,
    null等于.
   class等于class文件的目录
    classLoader等于bin目录
    / 是返回顶级目录,所有class返回class文件的目录的上级,而classLoacer返回是null

 

下面代码主要是用于得到jar目录中的文件
getResourceAsStream方法的效果是差不多,只是得到的对应路径的输入流,
参数可以指定bin(在jar文件,jar文件等同于bin)目录下的资源,而这个路径是相对bin的路径

properties.load(this.getClass().getResourceAsStream("/port.properties"));
properties.load(new FileReader(new File(SimpleMinaServer.class.getResource("/port.properties").toURI())));

SimpleMinaServer.class.getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " ")得到的jar目录

 

oadFilterConfig(filterProperties, ClassLoader.getSystemClassLoader());
        loadFilterConfig(filterProperties, Thread.currentThread().getContextClassLoader());

jdbcUtils.loadDriverClass

Thread.currentThread().getContextClassLoader().loadClass(className);

 Class.forName(className);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值