This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to get environment variable ?

 
Nathan KV
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Nathan
 
Ta Ri Ki Sun
Ranch Hand
Posts: 442
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use System.getProperty/ies
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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:
GetEnvVar.java

GETENVVAR.BAT

And here is the output:


Michael Morris
 
Eddie Sheffield
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic