Java如何获取当前的jar包路径

时间:2022-07-04 09:13:22
public LatticeAlgorithm(BinaryRelation bRel,RelationalContextEditor rce)
{
projectPath=this.getPath();//双击 && 右键打开方式Java...
if(projectPath.equals(""))//cmd窗口: java -jar *.jar
projectPath=System.getProperty("user.dir");
String javaProject=System.getProperty("user.dir");
//下面是javaproject和jar可执行文件的区别
if(LatticeAlgorithm.class.getResource("LatticeAlgorithm.class").toString().startsWith("file"))
projectPath=javaProject;//java工程中执行
binRel = bRel;
this.rce=rce;
lattice = new CompleteConceptLatticeImp();
}
private String getPath()
{
String filePath = System.getProperty("java.class.path");
String pathSplit = System.getProperty("path.separator");// windows下是";",linux下是":"

if (filePath.contains(pathSplit))
{
filePath = filePath.substring(0, filePath.indexOf(pathSplit));
} else if (filePath.endsWith(".jar"))
{// 截取路径中的jar包名,可执行jar包运行的结果里包含".jar"

// 此时的路径是"E:\workspace\Demorun\Demorun_fat.jar",用"/"分割不行
// 下面的语句输出是-1,应该改为lastIndexOf("\\")或者lastIndexOf(File.separator)
// System.out.println("getPath2:"+filePath.lastIndexOf("/"));
filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);

}
return filePath;
}