Java如何获得linux运行的jar包位置呢?

戚薇 Java经验 发布时间:2023-06-24 15:00:34 阅读数:13652 1
下文笔者讲述在linux中获取jar包位置的方法分享
学习完本篇之后,你将掌握获取jar包位置的方法,如下所示
使用
 Thread.currentThread()
    .getContextClassLoader()
	.getResource("").toString();
获取当前类所涉及的路径
    然后才能获取jar包运行位置
例:获取jar包位置的示例
 
package com.java265;
 
import java.io.File;
import java.util.Date;
 
public class TestJarPathAndFile {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path=Thread.currentThread().getContextClassLoader().getResource("").toString();
		path = path.substring(5,path.length());
		System.out.println("jar包目录:"+path);
		String folderName = "myfolder";
		String filePath = path+folderName;
		File file = new File(filePath);
		if(file.exists()&&file.isDirectory()) {
			String fileAbsolutePath = file.getAbsolutePath();//文件绝对路径
			System.out.println("找到了jar包同目录的文件夹:"+fileAbsolutePath);
			File[] childFiles = file.listFiles();
			for(File childFile:childFiles) {
				System.out.println("-childName:"+childFile.getName()+" 最后修改时间:"+new Date(childFile.lastModified()));
			}
		}else {
			System.out.println("文件夹在jar包同目录下不存在,或者不是文件夹");
		}
	}
 
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16875900836879.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者