2

If "java -jar" is run from a command line, is there a way to set local dos variable from java program so that after java is exited, it can still be present in the same session?

example

(cmd)
c:\java package.Class 

/*then in program you do something like 
'System.setVariable("name","value");'
*/

// java exited

echo %name%

value
EugeneP
  • 63
  • 1
  • 5
  • possible dupe of http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java – qwerty Jun 08 '11 at 09:41

3 Answers3

3

No. Processes cannot modify their parents' environment.

The best thing you can do is cheat a little and do either of the following:

  • Let the Java program write out a batch file in some known location and call it afterwards to set variables. Since batch files run in the current cmd process they can alter environment variables there.
  • Let the program output name/value pairs or complete set commands, catch the output and set the variables yourself afterwards. Goes wrong as soon as you want or have other output, I guess.
Joey
  • 344,408
  • 85
  • 689
  • 683
1

It's possible to set environment variables, according to question 2121795. However, I've never tried these methods so can't verify if they work.

If they do work, remember that setting an environment variable will not take effect in the current session (you'd need to restart the cmd window).

Community
  • 1
  • 1
hoipolloi
  • 7,984
  • 2
  • 27
  • 28
0

Also interesting is this question which has answers explaining how to use the Preferences API to modify the registry. I guess you should be able to modify environment variables via this route (didn't check thorougly).

Community
  • 1
  • 1
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
  • They don't get picked up by running processes for obvious reasons. – Joey Jun 08 '11 at 13:48
  • @Joey: OP's requirement is that environment variables are stil set after the Java program has exited, it was not explitly stated that they should be visible from the running Java program. – Adriaan Koster Jun 09 '11 at 07:12
  • They won't be visible from the process that started the Java program (which I interpret his »same session« as). – Joey Jun 09 '11 at 10:51
  • Maybe, I'm not 100% sure they are not, but that might just be my lack of knowledge (-: – Adriaan Koster Jun 09 '11 at 11:10