java打成jar包运行,和打成exe运行获取项目运行路径的工具类

1. 工具类

这里搜集了网上三种获取运行路径的方法,写了个工具类,具体如下:

package com.zgd.jar.utils;

import com.zgd.jar.App;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;

public class PathUtil {

    /**
     * 获取当前运行的目录
     * @return
     */
    public static String getRunPath(){
        /**
         * 方法一:获取当前可执行jar包所在目录
         */
        String filePath = System.getProperty("java.class.path");
        String pathSplit = System.getProperty("path.separator");//得到当前操作系统的分隔符,windows下是";",linux下是":"
        /**
         * 若没有其他依赖,则filePath的结果应当是该可运行jar包的绝对路径,
         * 此时我们只需要经过字符串解析,便可得到jar所在目录
         */
        if(filePath.contains(pathSplit)){
            filePath = filePath.substring(0,filePath.indexOf(pathSplit));
        }else if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
            filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        }
        return filePath;
    }

    public static String getJarPath(){
        /**
         * 方法二:获取当前可执行jar包所在目录
         */
        String filePath = "";
        URL url = App.class.getProtectionDomain().getCodeSource().getLocation();
        try {
            filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码,支持中文
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
            // 获取jar包所在目录
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        }

        File file = new File(filePath);
        filePath = file.getAbsolutePath();//得到windows下的正确路径
        return filePath;
    }

    public static String getExePath() throws IOException {
        return new File("").getAbsolutePath();
    }
}

2.main方法运行的app类

package com.zgd.jar;

import com.zgd.jar.utils.PathUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;

/**
 * Hello world!
 *
 */
public class App {

    private static Logger logger = LogManager.getLogger(App.class);


    public static void main( String[] args ) {
        String s = "\n" +
                "                                      \n" +
                "                                      \n" +
                "                                      \n" +
                "                                ,---, \n" +
                "       ,----,                 ,---.'| \n" +
                "     .'   .`|   ,----._,.     |   | : \n" +
                "  .'   .'  .'  /   /  ' /     |   | | \n" +
                ",---, '   ./  |   :     |   ,--.__| | \n" +
                ";   | .'  /   |   | .\\  .  /   ,'   | \n" +
                "`---' /  ;--, .   ; ';  | .   '  /  | \n" +
                "  /  /  / .`| '   .   . | '   ; |:  | \n" +
                "./__;     .'   `---`-'| | |   | '/  ' \n" +
                ";   |  .'      .'__/\\_: | |   :    :| \n" +
                "`---'          |   :    :  \\   \\  /   \n" +
                "                \\   \\  /    `----'    \n" +
                "                 `--`-'               \n";
        System.out.println(s);
        System.out.println("PathUtil.getRunPath():获取的路径是 "+ PathUtil.getRunPath());
        System.out.println("PathUtil.getJarPath():获取的路径是 "+ PathUtil.getJarPath());
        try {
            System.out.println("PathUtil.getExePath():获取的路径是 "+ PathUtil.getExePath());
        } catch (IOException e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() +"发生的异常是: ",e);
        }

        while (true){

        }
    }
}

3. 测试效果

分别打成jar包运行,和打成exe来运行,我们来分别测试下效果:
打成jar运行的方法
打成exe运行的方法

这里说一下我运行的目录位置: jar包是在C:\Users\Admin\Desktop\myapp文件夹中, exe是在C:\Users\Admin\Desktop桌面

3.1 打成jar包获取项目运行路径

这里写图片描述

3.2 打成exe包获取项目运行路径

这里写图片描述
可以看到第三种方法无论是jar还是exe都能很好的获取项目运行的根目录.

猜你喜欢

转载自blog.csdn.net/zzzgd_666/article/details/80756993