一此不安全的做法:
1. new File(path),這個方法的路徑到底在那裡取決於調用java命令的起始位置定義在哪裡,
tomcat/bin下面的catalina.bat調用了java,所以在tomcat下相對起始位置是tomcat/bin,但是eclipse啟動時,起始位置 是eclipse的項目路徑。
2.類.class.getClassLoader().getResource("").getPath()
如果使用了此方法,這把決定權交給了類載入器,例如tomcat的類載入是非委託機制的,而weblogic的類載入是委託的。大部分情況下是安全的。
3.類.class.getResource("")
這是個好方法,但局限性在於如果類檔案在jar中的話,那麼在打jar包時需要將檔案夾一起打進去,否則會返回null,jar檔案實際上就是zip檔案,zip檔案中:檔案就是檔案,檔案夾是檔案夾,不是關聯在一起的,很多開源的jar包就沒有把目錄打進去只打了classes檔案,雖然你能年到目錄階層,但是調用類.class.getResource("")會返回null.因為檔案的目錄結構和檔案夾本身是兩回事。
取得類路徑的安全做法:取得類本身在系統中隱藏檔位置,然後根據包層次一直找到classpath下面:
package com.wbtask;
import java.io.File;
import java.net.URL;
public class UrlUtil {
/**
* 取得當前類所在的檔案
* @param clazz
* @return
*/
public static File getClassFile(Class clazz){
URL path = clazz.getResource(clazz.getName().substring(
clazz.getName().lastIndexOf(".")+1)+".classs");
if(path == null){
String name = clazz.getName().replaceAll("[.]", "/");
path = clazz.getResource("/"+name+".class");
}
return new File(path.getFile());
}
/**
* 得到當前類的路徑
* @param clazz
* @return
*/
public static String getClassFilePath(Class clazz){
try{
return java.net.URLDecoder.decode(getClassFile(clazz).getAbsolutePath(),"UTF-8");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "";
}
}
/**
* 取得當前類所在的ClassPath目錄,比如tomcat下的classes路徑
* @param clazz
* @return
*/
public static File getClassPathFile(Class clazz){
File file = getClassFile(clazz);
for(int i=0,count = clazz.getName().split("[.]").length; i<count; i++)
file = file.getParentFile();
if(file.getName().toUpperCase().endsWith(".JAR!")){
file = file.getParentFile();
}
return file;
}
/**
* 取得當前類所在的ClassPath路徑
* @param clazz
* @return
*/
public static String getClassPath(Class clazz){
try{
return java.net.URLDecoder.decode(getClassPathFile(clazz).getAbsolutePath(),"UTF-8");
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return "";
}
}
public static void main(String[] args){
System.out.println(getClassFilePath(UrlUtil.class));
System.out.println(getClassPath(UrlUtil.class));
}
}
結果:
E:\Workspaces\MyProject\pjoName\target\classes\com\wbtask\UrlUtil.class
E:\Workspaces\MyProject\pjoName\target\classes