【沉浸式解决问题】System.getProperty(“user.dir“)获取不到项目根目录
目录
- 一、问题描述
- 二、场景还原
- 1. 测试类
- 2. 目录结构
- 3. 运行结果
- 三、原因分析
- 四、解决方案
- 1. 使用相对路径
- 2. 使用资源路径
一、问题描述
在微服务项目中使用System.getProperty(“user.dir”)获取不到父工程项目根目录,获取到的是当前子模块目录
二、场景还原
1. 测试类
package com.example.demo311;import org.junit.jupiter.api.Test;public class Temp2 {@Testvoid test1() {System.out.println(System.getProperty("user.dir"));}
}
2. 目录结构
3. 运行结果
三、原因分析
System.getProperty("user.dir")
实际上返回的是Java虚拟机(JVM)启动时的工作目录,而不是代码所在的目录。
换成同样路径下的main方法测试:
package com.example.demo311;public class Temp {public static void main(String[] args) {System.out.println(System.getProperty("user.dir"));}
}
就得到了想要的结果
猜测是junit启动时修改了JVM的路径参数
四、解决方案
如果不是在@Test中运行,那是没问题的,但如果你想我一样,使用System.getProperty("user.dir")
的方法需要传入不同的参数多次使用,同时又不是业务代码,只能在测试类里运行,那可以通过以下两种方式:
1. 使用相对路径
如果你知道项目结构,可以通过相对路径来定位根目录。
File rootDir = new File(System.getProperty("user.dir")).getParentFile();
System.out.println(rootDir.getAbsolutePath());
2. 使用资源路径
如果项目中有一个固定的资源文件,可以通过类加载器来获取项目的根目录。
URL resource = Temp2.class.getResource(Temp2.class.getSimpleName() + ".class");
if (resource != null) {String path = resource.getPath();File rootDir = new File(path).getParentFile().getParentFile().getParentFile();System.out.println(rootDir.getAbsolutePath());
}
喜欢的点个关注吧><!祝你永无bug!
/*_ooOoo_o8888888o88" . "88(| -_- |)O\ = /O____/`---'\____.' \\| |// `./ \\||| : |||// \/ _||||| -:- |||||- \| | \\\ - /// | || \_| ''\---/'' | |\ .-\__ `-` ___/-. /___`. .' /--.--\ `. . __."" '< `.___\_<|>_/___.' >'"".| | : `- \`.;`\ _ /`;.`/ - ` : | |\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^佛祖保佑 永无BUG
*/