JAVA獲取程序(打成jar或classpath)所在目錄


一、簡述

  JAVA獲取程序(打成jar或classpath)所在目錄。

二、代碼

package dearcloud.utils.context;

import dearcloud.utils.StringUtils;

import java.io.File;

public class AppContext {
    public static String baseDirectory() {
        try {
            String path = ClassLoader.getSystemResource("").getPath();
            if (StringUtils.isNullOrEmpty(path))
                return getProjectPath();
            return path;
        } catch (Exception ignored) {
        }
        return getProjectPath();
    }

    private static String getProjectPath() {
        java.net.URL url = AppContext.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(File.separatorChar) + 1);
        java.io.File file = new java.io.File(filePath);
        filePath = file.getAbsolutePath();
        return filePath;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM