1. 程式人生 > >Java中使用Jar包時讀取當前jar檔案所在的目錄工具

Java中使用Jar包時讀取當前jar檔案所在的目錄工具

在實際使用中,jar包所放的位置是不一定的所以要動態獲取當前目錄

package com.gj5u.publics.util;

import java.io.File;

/**
 * 獲取打包後jar的路徑資訊
 * 
 * @author Rex
 */
public class JarToolUtil
{
    /**
     * 獲取jar絕對路徑
     * 
     * @return
     */
    public static String getJarPath()
    {
        File file = getFile();
        if (file == null)
            return null;
        return file.getAbsolutePath();
    }
    
    /**
     * 獲取jar目錄
     * 
     * @return
     */
    public static String getJarDir()
    {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getParent();
    }
    
    /**
     * 獲取jar包名
     * 
     * @return
     */
    public static String getJarName()
    {
        File file = getFile();
        if (file == null)
            return null;
        return getFile().getName();
    }
    
    /**
     * 獲取當前Jar檔案
     * 
     * @return
     */
    private static File getFile()
    {
        // 關鍵是這行...
        String path = JarToolUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try
        {
            path = java.net.URLDecoder.decode(path, "UTF-8"); // 轉換處理中文及空格
        }
        catch (java.io.UnsupportedEncodingException e)
        {
            return null;
        }
        return new File(path);
    }
}