普通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. }  

 原文地址:http://she.iteye.com/blog/1199723

你可能感兴趣的:(WEB-INF)