本文参考
- this.class.getProtectionDomain().getCodeSource().getLocation()
- 取得程序以后门路System.getProperty(“user.dir”)
封装在jar包外面,执行jar包,获取以后jar包的绝对路径System.getProperty("java.class.path")
Java获取以后class的绝对路径
try {
String path = new File(PathTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
System.out.println("path: " + path);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
Java获取我的项目根目录System.getProperty("user.dir")
System.getProperty(“user.dir”)
- 开发环境时,user.dir 指向的是我的项目的根目录
- windows,将我的项目部署到tomcat下,user.dir指向的门路是以后用户的桌面
- linux环境下,将我的项目部署到tomcat中,user.dir指向的门路为tomcat的bin目录
Java我的项目中获取门路的办法
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
public class PathTest {
public static void main(String[] args) throws MalformedURLException, URISyntaxException {
// 以后class的绝对路径
try {
String path = new File(PathTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
System.out.println("path: " + path);
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
// 以后class的绝对路径(classpath门路)
String classpath = PathTest.class.getResource("/").getPath().replaceFirst("/", "");
System.out.println("classpath: " + classpath);
// Java 装置目录
System.out.println("java.home : " + System.getProperty("java.home"));
// Java 类格局版本号
System.out.println("java.class.version : " + System.getProperty("java.class.version"));
// Java 类门路
System.out.println("java.class.path : " + System.getProperty("java.class.path"));
// 加载库时搜寻的门路列表
System.out.println("java.library.path : " + System.getProperty("java.library.path"));
// 默认的临时文件门路
System.out.println("java.io.tmpdir : " + System.getProperty("java.io.tmpdir"));
// 要应用的 JIT 编译器的名称
System.out.println("java.compiler : " + System.getProperty("java.compiler"));
// 一个或多个扩大目录的门路
System.out.println("java.ext.dirs : " + System.getProperty("java.ext.dirs"));
// 用户的账户名称
System.out.println("user.name : " + System.getProperty("user.name"));
// 用户的主目录
System.out.println("user.home : " + System.getProperty("user.home"));
// 以后工程门路
System.out.println("user.dir : " + System.getProperty("user.dir"));
System.out.println("package: " + PathTest.class.getPackage().getName());
System.out.println("package: " + PathTest.class.getPackage().toString());
String packName = PathTest.class.getPackage().getName();
URI packuri = new URI(packName);
System.out.println(packuri.getPath());
System.out.println(packName.replaceAll("//.", "/"));
System.out.println(System.getProperty("user.dir") + "\\" + (PathTest.class.getPackage().getName()).replaceAll("//", "/") + "\\");
}
}
发表回复