Reputation: 3394
Everywhere I search, it says you can get an environment variable by using System.getenv(str).
It's not working for me. Here's what I am doing: OS : Mac OS x 10.7 Java 1.6.x
If I do export abc=/hello/
in my terminal and then echo $abc
, it gives me the variable. If I close the terminal, reopen it again and do echo $abc
, it's gone. To overcome this, I edited my .bash_profile
file and inserted export abc=/hello/
. Close the terminal, do echo $abc
and it works. So I understood that the env variable is permanent now.
Now if in my java console app, I print System.getenv("abc")
, it returns null
. What am I missing?
Upvotes: 5
Views: 6216
Reputation: 1
I too faced The same issue , I resolved it this way.
Open Terminal
cd to the folder where eclipse.app is located E.g cd /Users/Shared/eclipse/jee-2020-09
Type open Eclipse.app/
Eclipse will now open and will be able to access the system environment variables as well.
Check it using the code:
System.getenv().forEach((k, v) -> {
System.out.println("ENV : " + k + ":" + v);
});
Upvotes: 0
Reputation: 23802
Eclipse does not use the system's env variables unless launched directly from the shell (which is how it is generally launched, by clicking its icon). In that case you will have to explicitly set the required env variables in the environment tab of the run configuration of the program.
Upvotes: 3
Reputation: 59617
The reason that you needed to put the export
in your .bash_profile
is that setting environment variables in a shell only persist the variables in that shell, and - since you used export
- to children of that shell, or in other words, other programs launched by that shell.
If you're running your java code from Eclipse, and you launch Eclipse from a shell with your environment variables set, then your program should see the added environment variables. To launch Eclipse from the shell, you'll need to use the OS X open
command:
$ open /Applications/eclipse/Eclipse.app
Alternately, you can set the environment variables within your Eclipse project, and you'll need to do this if you're not launching Eclipse from a shell with the proper environment. In the Run Configurations dialog, look for a tab named Environment. Here you'll find a table for adding environment variables that will be passed to your program.
It's better to add the environment variables to the Run Configuration since that way they'll always be available to your project. Your code doesn't actually care where the environment variables are coming from, and adding them to the project is simpler, and will work the same way on different platforms.
Of course, when you run your program outside Eclipse, you'll need to make sure that the same environment variables exist in the shell where you e.g. run java
.
Upvotes: 8