当环境变量存在时,System.getenv()返回null [英] System.getenv() returns null when the environment variable exists

查看:126
本文介绍了当环境变量存在时,System.getenv()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 System.getenv()来获取我通过终端(Mac)设置的环境变量的值,我还将变量设置为我的.bash_profile文件并重新加载。在这样做之后,我回显了值并且正确的值被打印到终端。尝试检索变量的值时(我确保在我的.bash_profile文件和使用 System.getenv()时使用了正确的名称。

I am trying to System.getenv() to get the value of an environment variable that I have set through my terminal (Mac), I also set the variable in my .bash_profile file and reloaded. After doing so, I echo'd the value and the correct value was printed to the terminal. When trying to retrieve the value of the variable (I made sure I was using the correct name in both my .bash_profile file and when using System.getenv().

在下面的代码中,我已使用 VAR_NAME 替换了变量的名称:

In the below code, I have replaced the name of the variable with VAR_NAME:

String varValue = System.getenv("VAR_NAME");
System.out.println("Value: " + varValue);

在我的.bash_profile中:

In my .bash_profile:

export VAR_NAME="foo"

当我打印出的值时,会打印null varValue

这可能是什么原因造成的?

What could be the cause of this?

编辑:我按照最佳答案这里,重新启动Eclipse并且工作正常!

I followed the top answer here, restarted Eclipse and it worked!

推荐答案

回答这个问题比仅仅 Java中的System.getenv()。

环境变量仅在进程树下进行,并且仅在进程启动时才进行。 Eclipse是shell的子进程 - 因此,它继承了在shell上定义的所有环境变量当你启动Eclipse 时。

The environment variables go only down the process tree and only when a process is launched. Eclipse is a child process of your shell - hence, it inherited all the environment variables that had been defined on your shell when you launched Eclipse.

您可能已经在启动Eclipse之后在shell 上定义了环境变量。因此,Eclipse和它创建的子Java进程永远不会知道你的新环境变量。

You probably defined the environment variable on your shell after you had launched Eclipse. Hence, Eclipse and the child Java processes it created, would never "know" about your new environment variable.

由于这种行为,实际上这里的解决方案是退出Eclipse并从shell再次启动它,其中已定义环境变量 。另一种选择是转到项目的运行配置并在那里定义环境变量。

Due to this behavior, actually the solution here is to exit Eclipse and launch it again from your shell, in which the environment variable is already defined. Another option is to go to the run configuration of the project and define there the environment variable.

这篇关于当环境变量存在时,System.getenv()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆