Java取得當前類的路徑

來源:互聯網
上載者:User

一此不安全的做法:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.