java 获取当前路径_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2208 | 回复: 0   主题: java 获取当前路径        下一篇 
    本主题由 hui.chen 于 2015-7-30 15:23:14 移动
wlcbhrss
注册用户
等级:新兵
经验:68
发帖:65
精华:0
注册:2011-8-21
状态:离线
发送短消息息给wlcbhrss 加好友    发送短消息息给wlcbhrss 发消息
发表于: IP:您无权察看 2015-7-28 17:35:48 | [全部帖] [楼主帖] 楼主

java获取当前项目路径:

  • object.class.getResource()方法获得当前生成的class的绝对路径(此方法在jar包中无效,因为他获得的是生成的class的路径,返回的内容最后包含/)
  1. //当前的类名就是:GetFilePath
  2. publicstatic String getFilePath(String fileName)  
  3.     {  
  4.         String path = GetFilePath.class.getResource("").toString();  
  5. if (path != null)  
  6.         {  
  7.             path = path.substring(5, path.indexOf("WEB-INF") + 8);

    //如果是windwos将5变成6

  8. //System.out.println("current path :" + path);
  9.         }  
  10. return (path + fileName);  
  11.     }  

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

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

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

  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. return rootPath;         
  10.    }  




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

例如 项目在 D:\workspace\testPorjject

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

System.out.println(System.getProperty("user.dir"));

//user.dir指定了当前的路径 

  • 使用File提供的函数获取当前路径: 
  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中:

request.getContextPath()
request.getSession().getServletContext().getRealPath()


servlet中:

this.getServletContext().getRealPath("/");
this.getServlet().getServletContext().getRealPath("/");


--转自 北京联动北方科技有限公司

该贴由hui.chen转至本版2015-7-30 15:23:13



赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论