import java.io.File;
public class ProjectPathExample {
public static void main(String[] args) {
// 获取项目的根路径
String projectPath = System.getProperty("user.dir");
System.out.println("项目根路径: " + projectPath);
// 获取当前类所在的路径
String classPath = ProjectPathExample.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("当前类所在路径: " + classPath);
// 获取某个文件的绝对路径
File file = new File("example.txt");
String absolutePath = file.getAbsolutePath();
System.out.println("example.txt 的绝对路径: " + absolutePath);
}
}
获取项目的根路径:
System.getProperty("user.dir") 返回当前工作目录,通常是指项目的根目录。获取当前类所在的路径:
ProjectPathExample.class.getProtectionDomain().getCodeSource().getLocation().getPath() 返回当前类所在的 JAR 文件或类文件的路径。获取某个文件的绝对路径:
file.getAbsolutePath() 返回指定文件的绝对路径。这里以 example.txt 为例,实际使用时可以根据需要替换为其他文件名。希望这些代码和解释能帮助你更好地理解如何在 Java 中获取项目路径。
上一篇:java 反射获取属性值
下一篇:java setscale
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站