【沉浸式解决问题】System.getProperty(“user.dir“)获取不到项目根目录

目录

一、问题描述

在微服务项目中使用System.getProperty("user.dir")获取不到父工程项目根目录,获取到的是当前子模块目录


二、场景还原

1. 测试类

java 复制代码
package com.example.demo311;

import org.junit.jupiter.api.Test;


public class Temp2 {
    @Test
    void test1() {
        System.out.println(System.getProperty("user.dir"));
    }
}

2. 目录结构

3. 运行结果


三、原因分析

System.getProperty("user.dir")实际上返回的是Java虚拟机(JVM)启动时的工作目录,而不是代码所在的目录。

换成同样路径下的main方法测试:

java 复制代码
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. 使用相对路径

如果你知道项目结构,可以通过相对路径来定位根目录。

java 复制代码
File rootDir = new File(System.getProperty("user.dir")).getParentFile();
System.out.println(rootDir.getAbsolutePath());

2. 使用资源路径

如果项目中有一个固定的资源文件,可以通过类加载器来获取项目的根目录。

java 复制代码
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!

txt 复制代码
/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            佛祖保佑       永无BUG
*/
相关推荐
马士兵教育12 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
snow@li12 小时前
Java:理解 Gradle / 后端项目的管家 / 打包SpringBoot 应用 / 完成编译、下载依赖、运行测试、打包 JAR/WAR / 速查表
java
云烟成雨TD12 小时前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
zfoo-framework13 小时前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java
逍遥德13 小时前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt
云烟成雨TD13 小时前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring
weixin_5231853213 小时前
Collections.unmodifiableMap详解:真的不可修改吗?
java·linux·前端
点燃大海13 小时前
SpringAI构建智能体
java·spring boot·spring·springai智能体
xier_ran13 小时前
【infra之路】02_RadixAttention与KV_Cache管理
java·spring boot·spring
黑马师兄13 小时前
RAG混合检索深度解析:让AI真正找到你要的内容
java·人工智能·ai·agent·rag·ai-native