【问题标题】:System variable set on mac terminal is not available from java appllication在 mac 终端上设置的系统变量在 java 应用程序中不可用
【发布时间】:2020-03-13 17:02:13
【问题描述】:

我将它添加到 ~/.bash_profile 的底部

TEST_VAR=testPass
export TEST_VAR

然后在mac终端上执行source ~/.bash_profile

我现在可以使用 - echo $TEST_VAR 打印出值

从我的 java 应用程序中,System.getProperty("TEST_VAR")System.getenv("TEST_VAR") 返回 null。

当我使用

列出 java 应用程序中的所有环境变量时,新变量未显示
System.getProperties().entrySet().forEach(System.out::println);

【问题讨论】:

    标签: java macos operating-system environment-variables


    【解决方案1】:

    您可以使用以下代码获得所需的结果:

    public class TestExportProp {
        public static void main(String args[]) {        
            System.out.println(System.getenv("TEST_ENV_VAR"));
        }
    }
    

    请注意,您需要在设置环境变量的地方执行此代码,例如

    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: export TEST_ENV_VAR=varTest
    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: echo $TEST_ENV_VAR
    varTest
    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: javac TestExportProp.java 
    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: java TestExportProp
    varTest
    

    如果要读取所有变量,可以使用以下代码:

    Map <String, String> map = System.getenv();
    for (Map.Entry <String, String> entry: map.entrySet()) {
        System.out.println("Environment variable: " + entry.getKey() + " Value: " + entry.getValue());
    }
    

    更新:

    我可以看到您已更新您的问题。请注意,该解决方案在没有任何更改的情况下仍然有效,即在执行source ~/.bash_profile 之后,将目录更改为您的班级所在的位置并运行您的班级,例如

    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: javac TestExportProp.java 
    [~/Documents/workspace-spring-tool-suite-4-4.4.0.RELEASE/AdHoc/src]: java TestExportProp
    testPass
    

    【讨论】:

    • 如果我想读取来自~/.bash_profile的变量怎么办
    • 但这是否意味着 java 应用程序必须部署在与 bash_profile 相同的文件夹中?
    • 好的,但是从 IDE 运行时这不起作用,我使用的是 IntelliJ 并且无法打印变量?
    • 好的,你说得对,我接受答案。我认为这只是一个 IDE 问题,然后一旦我在服务器/ec2 上部署我的 JAR,它应该可以正常检索变量?
    猜你喜欢
    • 2023-03-28
    • 2015-07-31
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多