封装在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("//", "/") + "\\");

本文参考封装在jar包里面,执行jar包,获取当前jar包的绝对路径System.getProperty("java.class.path")Java获取当前class的绝对路径try {String path = new File(PathTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath...