---
title: "java获取当前工程目录"
author: "yrandy"
date: "2012-08-23T17:41:17Z"
tags: []
categories: ["移动开发"]
slug: "java"
draft: false
lastmod: "2012-08-23T17:41:17Z"
id: 1660131
url: "https://yrandy.iteye.com/blog/1660131"
---

转载自：[http://blog.csdn.net/yangzhongwei1031/article/details/1830668](http://blog.csdn.net/yangzhongwei1031/article/details/1830668)

public class PathUtil {

public static void main(String\[] args)throws Exception {  
   PathUtil p = new PathUtil();  
   System.out.println(p.getWebClassesPath());  
   System.out.println(p.getWebInfPath());  
   System.out.println(p.getWebRoot());  
}

public String getWebClassesPath() {  
   String path = getClass().getProtectionDomain().getCodeSource()  
     .getLocation().getPath();  
   return path;  
    
}

public String getWebInfPath() throws IllegalAccessException{  
   String path = getWebClassesPath();  
   if (path.indexOf("WEB-INF") &gt; 0) {  
    path = path.substring(0, path.indexOf("WEB-INF")+8);  
   } else {  
    throw new IllegalAccessException("路径获取错误");  
   }  
   return path;  
}

public String getWebRoot() throws IllegalAccessException{  
   String path = getWebClassesPath();  
   if (path.indexOf("WEB-INF") &gt; 0) {  
    path = path.substring(0, path.indexOf("WEB-INF/classes"));  
   } else {  
    throw new IllegalAccessException("路径获取错误");  
   }  
   return path;  
}  
}