普通JAVA获取WEB项目下的WEB-INF目录

  JAVA Web项目获取物理根目录绝对路径  

Java代码   收藏代码
  1. package com.path;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4. import java.net.URL;  
  5. import java.net.URLDecoder;  
  6.   
  7. /** 
  8.  * 普通JAVA获取   WEB项目下的WEB-INF目录 
  9.  * @author wang 
  10.  * 
  11.  */  
  12. public class PathUtil {  
  13.     public static void main(String[] args) {  
  14.         PathUtil pathUtil = new PathUtil();  
  15.         System.out.println("path=="+pathUtil.getWebInfPath());  
  16.     }  
  17.       
  18.     private String getWebInfPath(){  
  19.         URL url = getClass().getProtectionDomain().getCodeSource().getLocation();  
  20.         String path = url.toString();  
  21.         int index = path.indexOf("WEB-INF");  
  22.           
  23.         if(index == -1){  
  24.             index = path.indexOf("classes");  
  25.         }  
  26.           
  27.         if(index == -1){  
  28.             index = path.indexOf("bin");  
  29.         }  
  30.           
  31.         path = path.substring(0, index);  
  32.           
  33.         if(path.startsWith("zip")){//当class文件在war中时,此时返回zip:D:/...这样的路径  
  34.             path = path.substring(4);  
  35.         }else if(path.startsWith("file")){//当class文件在class文件中时,此时返回file:/D:/...这样的路径  
  36.             path = path.substring(6);  
  37.         }else if(path.startsWith("jar")){//当class文件在jar文件里面时,此时返回jar:file:/D:/...这样的路径  
  38.             path = path.substring(10);   
  39.         }  
  40.         try {  
  41.             path =  URLDecoder.decode(path, "UTF-8");  
  42.         } catch (UnsupportedEncodingException e) {  
  43.             e.printStackTrace();  
  44.         }  
  45.           
  46.         return path;  
  47.     }  
  48. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值