Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading environment variables from java using Eclipse

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?

like image 308
samach Avatar asked Dec 20 '22 16:12

samach


1 Answers

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.

like image 192
pb2q Avatar answered Dec 24 '22 01:12

pb2q