java 项目 获取当前路径

转自http://blog.csdn.net/hpf911/article/details/5852127

java获取当前项目路径:

  • object.class.getResource()方法获得当前生成的class的绝对路径(此方法在jar包中无效,因为他获得的是生成的class的路径,返回的内容最后包含/)

 

[c-sharp]  view plain copy
  1. //当前的类名就是:GetFilePath  
  2. public static String getFilePath(String fileName)  
  3.     {  
  4.         String path = GetFilePath.class.getResource("").toString();  
  5.   
  6.         if (path != null)  
  7.         {  
  8.             path = path.substring(5, path.indexOf("WEB-INF") + 8);//如果是windwos将5变成6  
  9.             //System.out.println("current path :" + path);  
  10.         }  
  11.         return (path + fileName);  
  12.     }  
 

  • getClass().getResource() 方法获得相对路径( 此方法在jar包中无效。返回的内容最后包含/)

例如 项目在/D:/workspace/MainStream/Test

在javaProject中,getClass().getResource("/").getFile().toString() 返回:/D:/workspace/MainStream/Test/bin/


[java]  view plain copy
  1. public String getCurrentPath(){  
  2.        //取得根目录路径  
  3.        String rootPath=getClass().getResource("/").getFile().toString();  
  4.        //当前目录路径  
  5.        String currentPath1=getClass().getResource(".").getFile().toString();  
  6.        String currentPath2=getClass().getResource("").getFile().toString();  
  7.        //当前目录的上级目录路径  
  8.        String parentPath=getClass().getResource("../").getFile().toString();  
  9.          
  10.        return rootPath;         
  11.   
  12.    }  



  • 利用System.getProperty()函数获取当前路径,得到项目文件夹的根目录,不带/ 

例如 项目在 D:\workspace\testPorjject

者System.getProperty("user.dir") 返回 D:\workspace\testPorjject 

[java]  view plain copy
  1. System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径   
 

  • 使用File提供的函数获取当前路径: 

[java]  view plain copy
  1. File directory = new File("");//设定为当前文件夹   
  2. try{   
  3.     System.out.println(directory.getCanonicalPath());//获取标准的路径   
  4.     System.out.println(directory.getAbsolutePath());//获取绝对路径   
  5. }catch(Exceptin e){}   
 

  •  web 项目中 

 jsp中:

 

[java]  view plain copy
  1. request.getContextPath()  
  2. request.getSession().getServletContext().getRealPath()     
 

 

servlet中:

[java]  view plain copy
  1. this.getServletContext().getRealPath("/");  
  2. this.getServlet().getServletContext().getRealPath("/");  
 

或者:

File file = new File("/lib/adb.exe");
String path = file.getAbsolutePath();
System.out.println(path);


或者:

 // 当前路径
        String path = System.getProperty("user.dir");
        String propertyPath = "当前路径: "+path;
        // 完整路径
        path = System.getProperty("java.class.path");
        String fullPath = "完整路径: "+path;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值