欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

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;
    }
}

 

posted @ 2019-01-09 17:57  宋兴柱  阅读(3017)  评论(0编辑  收藏  举报