獲取Java程式執行的路徑 | 獲取當前jar包的路徑
經過試驗,不管是否是Jar包,不管是否是Tomcat部署,以下三個方法均可實現。
packagetest;
publicclassMyPath {
publicstaticString getProjectPath() {
java.net.URL url = MyPath.class.getProtectionDomain().getCodeSource().getLocation();
String filePath =null;
try{
filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");
}catch(Exception e) {
e.printStackTrace();
}
if(filePath.endsWith(".jar"))
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
java.io.File file =newjava.io.File(filePath);
filePath = file.getAbsolutePath();
returnfilePath;
}
publicstatic
String realPath = MyPath.class.getClassLoader().getResource("").getFile();
java.io.File file =newjava.io.File(realPath);
realPath = file.getAbsolutePath();
try{
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
}catch(Exception e) {
e.printStackTrace();
}
returnrealPath;
}
publicstaticString getAppPath(Class<?> cls){
//檢查使用者傳入的引數是否為空
if(cls==null)
thrownewjava.lang.IllegalArgumentException("引數不能為空!");
ClassLoader loader=cls.getClassLoader();
//獲得類的全名,包括包名
String clsName=cls.getName();
//此處簡單判定是否是Java基礎類庫,防止使用者傳入JDK內建的類庫
if(clsName.startsWith("java.")||clsName.startsWith("javax.")) {
thrownewjava.lang.IllegalArgumentException("不要傳送系統類!");
}
//將類的class檔案全名改為路徑形式
String clsPath= clsName.replace(".", "/")+".class";
//呼叫ClassLoader的getResource方法,傳入包含路徑資訊的類檔名
java.net.URL url =loader.getResource(clsPath);
//從URL物件中獲取路徑資訊
String realPath=url.getPath();
//去掉路徑資訊中的協議名"file:"
intpos=realPath.indexOf("file:");
if(pos>-1) {
realPath=realPath.substring(pos+5);
}
//去掉路徑資訊最後包含類檔案資訊的部分,得到類所在的路徑
pos=realPath.indexOf(clsPath);
realPath=realPath.substring(0,pos-1);
//如果類檔案被打包到JAR等檔案中時,去掉對應的JAR等打包檔名
if(realPath.endsWith("!")) {
realPath=realPath.substring(0,realPath.lastIndexOf("/"));
}
java.io.File file =newjava.io.File(realPath);
realPath = file.getAbsolutePath();
try{
realPath=java.net.URLDecoder.decode(realPath,"utf-8");
}catch(Exception e){
thrownewRuntimeException(e);
}
returnrealPath;
}//getAppPath定義結束
}
使用Jar包,在Tomcat的執行結果如下:
ProjectPath: D:\J2EE\Tomcat 6.0\webapps\MyService1WebP\WEB-INF\lib
RealPath: D:\J2EE\Tomcat 6.0\webapps\MyService1WebP\WEB-INF\classes
Apppath: D:\J2EE\Tomcat 6.0\webapps\MyService1WebP\WEB-INF\classes