Hovav
Hovav

Reputation: 151

Create an environment variable programmatically

I have an external program that I'm running. for some reason, the code owner didn't give me the code or and good documentation, I know how to run this code but it was written originaly to be executed from command line and not from JAVA. the effect on me is that this application uses an ENV variable and relay on its value (a path on the computer for the output). I want to change that value, how can it be done without running it from a batch file?

Upvotes: 0

Views: 5573

Answers (4)

mprabhat
mprabhat

Reputation: 20323

In your command prompt first set the required variable

set FILELOCATION=<PATH TO FILE>

java MyProgram

In this case the FILELOCATION will be available till you close the program.

Not setting variable will be dependent on OS.

For Linux or Solaris you can do :

export FILELOCATION=<PATH TO FILE>

In case you are looking for command line parameters then you can use something like this:

java MyProgram PathToFile

There is a better way of doing this java -DFILELOCATION=<PATH_TO_FILE> MyProgram

Edit: As per comment.

Just use ProcessBuilder to set ENV variable in Java code.

Upvotes: 0

ewan.chalmers
ewan.chalmers

Reputation: 16235

I assume you are executing this program using one of the Runtime.exec() methods in Java code to create a Process.

Note that some of those methods allows you to pass environment variables to the process you are creating, for example exec(String[] cmd, String[] envp).

Alternatively, the Map returned by ProcessBuilder.environment() can be manipulated for the same effect.

Upvotes: 1

brimborium
brimborium

Reputation: 9512

See this post. It usually helps to first start a search here before posting a question. If you already tried that solution, it really helps the Helpers to let them know that you tried it and what went wrong.

Upvotes: 0

Vadzim
Vadzim

Reputation: 26160

how can it be done without running it from a batch file

Just set global environment variable. All new processes will see it (excluding those inheriting environment from old parent process).

See also How do I set environment variables from Java?. This answers the question's title. Which doesn't match the question's body, btw. ;)

Upvotes: 0

Related Questions