JAVA路径获取方法

以下给出获取JAVA路径的常用方法,用于解决文件路径获取的问题


public class test2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

        //用户的当前工作目录,一般不建议使用这种方式
        System.out.println("System.getProperty(\"user.dir\")======"+System.getProperty("user.dir")); 
        //当前类文件的URI目录
        System.out.println("test2.class.getResource(\"\")========"+test2.class.getResource(""));
        //当前的classpath的绝对URI路径。
        System.out.println("test2.class.getResource(\"/\")=========="+test2.class.getResource("/"));
      //同上,当前的classpath的绝对URI路径,推荐使用
        System.out.println("Thread.currentThread().getContextClassLoader().getResource(\"\")====="+Thread.currentThread().getContextClassLoader().getResource(""));
      //同上,当前的classpath的绝对URI路径。
        System.out.println("test.class.getClassLoader().getResource(\"\")=========="+test2.class.getClassLoader().getResource(""));
        //同上,得到的也是当前ClassPath的绝对URI路径。
        System.out.println("ClassLoader.getSystemResource(\"\")==========="+ClassLoader.getSystemResource(""));
        
        //path不能以'/'开头时,path是指类加载器的加载范围,在资源加载的过程中,使用的逐级向上委托的形式加载的,'/'表示Boot ClassLoader中的加载范围,因为这个类加载器是C++实现的,所以加载范围为null
        System.out.println(test2.class.getClassLoader().getResource(""));
        System.out.println(test2.class.getClassLoader().getResource("/"));				
	}

}

输出结果如下

System.getProperty("user.dir")======C:\test11\eclipse\workspace\log4jtest
test2.class.getResource("")========file:/C:/test11/eclipse/workspace/log4jtest/bin/log4jtest/
test2.class.getResource("/")==========file:/C:/test11/eclipse/workspace/log4jtest/bin/
Thread.currentThread().getContextClassLoader().getResource("")=====file:/C:/test11/eclipse/workspace/log4jtest/bin/
test.class.getClassLoader().getResource("")==========file:/C:/test11/eclipse/workspace/log4jtest/bin/
ClassLoader.getSystemResource("")===========file:/C:/test11/eclipse/workspace/log4jtest/bin/
file:/C:/test11/eclipse/workspace/log4jtest/bin/
null


推荐文章

http://blog.youkuaiyun.com/shendl/article/details/1427475


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值