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
1

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

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).

4 Comments

They don't get picked up by running processes for obvious reasons.
@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.
They won't be visible from the process that started the Java program (which I interpret his »same session« as).
Maybe, I'm not 100% sure they are not, but that might just be my lack of knowledge (-:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.