File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes How to get environment variable ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to get environment variable ?" Watch "How to get environment variable ?" New topic

How to get environment variable ?

Nathan KV

Joined: Aug 09, 2001
Posts: 25
i am setting the environment variable in dos by giving the following command.
set empid=1001
how to get the value of empid in my java program ?
Thx in advance.
Ta Ri Ki Sun
Ranch Hand

Joined: Mar 26, 2002
Posts: 442
use System.getProperty/ies
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Greetings Nathan,
Welcome to JavaRanch, the absolute best site on the www for Java information. We don't have many rules around here, but we do have one. Please change your display name to a first and last name to conform with the JavaRanch Naming Policy.
You can change it here: Change your display name.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451

use System.getProperty/ies

That won't work since the System properties file is limited to environment variables which are required by the VM and core Java API. I'm afraid that you are limited to a couple of options, first write an native method to retrieve the dos environment, or write a simple batch file and parse the output. Here is an example of the second method:


And here is the output:

Michael Morris
Eddie Sheffield

Joined: Oct 23, 2002
Posts: 21
Originally posted by Taariq Levack:
use System.getProperty/ies

As Michael said this works for the "default" environment variables. However it also works for system variables defined on the command line when the app is run. So for example you could run the app as:

You would then have the system property "username" defined inside your app. You can include as many "-Dname=value" pairs as you want (subject to OS command line length limits ) This would be the Windows way of running it. You can do something similar in *nix. A batch file or shell script to start up the app is helpful. Do some searching on the web - this is an old problem and you should be able to find several solutions. I think I've even seen generic batch/shell scripts that would add all available env vars to the command line, but that may be overkill.
Good luck!
[ April 01, 2003: Message edited by: Eddie Sheffield ]

"When you find yourself in the company of a halfling and an ill-tempered Dragon, remember, you do not have to outrun the Dragon. You just have to outrun the halfling."
I agree. Here's the link:
subject: How to get environment variable ?
It's not a secret anymore!