1

Is it possible to run a batch file under windows as if it were running from the same shell that was running the java instance (as opposed to in a new console instance)?

There is a batch file that I want to run that is provided by a third party and sets a bunch of environment variables conditionally that I would much rather not have to translate into Java, but that are needed for certain things in the Java app to work.

I know the alternative is to manually run the batch file in a command prompt before running the Jar to get the same effect, but in this scenario that would require either a lot of typing or a lot of customized batch files.

Community
  • 1
  • 1
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145

1 Answers1

3

Short answer: no.

When you state "running from the same shell that was running the java instance" you seem to suggest that the shell & java are co-existing at some common/shared level. Their relationship is, instead, hierarchical: the shell is a parent process, and it started java as a child process.

Any changes that a process makes (such as your batch process) to the environment are:

  • visible to that process, and
  • visible to child processes, but
  • never to a parent process.

The reason the batch file, when executed from the command prompt, causes immediate changes to the current environment is that the command shell (cmd.exe) is designed to process batch files "in place" - without starting a new process [under unix, the shell would "source" a script file to do much the same thing].

Java, not being "cmd.exe", doesn't do this. As you've noted, running a batch file from java will create a new command processor as a child process, which on completion has no effect on the java environment.

Options include:

  1. Write a batch file to
    • call your other batch file, then
    • start your java process, OR
  2. Parse the batch file by your java program. If you "mandate" that the only valid content of your "batch file" are simple assignment statements of the form "X=Y", then this isn't too difficult - you might in fact load it as a Properties file.
Richard Sitze
  • 8,262
  • 3
  • 36
  • 48