【Java 路径】运行可执行jar包获取相关路径

一、获取可执行jar包所在目录

(1)方法一:使用

System.getProperty("java.class.path")

获取classpath的路径,若没有其他依赖,在cmd下运行该可执行jar包,则该值即为该jar包的绝对路径。代码如下:

/**
 * 方法一:获取当前可执行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);
}
System.out.println("jar包所在目录:"+filePath);

(2)方法二:使用

ClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath()

但是这种方法不支持中文,需要使用以下代码方法,进行转换

/**
 * 方法二:获取当前可执行jar包所在目录
 */
URL url = JarTest.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下的正确路径
System.out.println("jar包所在目录:"+filePath);

二、获取当前JVM运行目录

使用:

System.getProperty("user.dir")

三、获取jar包内的资源文件

文件与classes在同一目录下,或者使用maven构建时,文件存在于resources文件夹下,可以使用:
getResourceAsStream
代码如下:

/**
 * 读取jar包中的资源文件
 */
InputStream is = JarTest.class.getResourceAsStream("/test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s="";
try {
    while((s=br.readLine())!=null)
        System.out.println(s);
} catch (IOException e) {
    e.printStackTrace();
}
  • 17
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值