简体   繁体   中英

How to set .bat environment variables to ProcessBuilder process

I need to execute .bat file from the application installation location which has only SET commands from my java program.

I tried to run as shown below

ProcessBuilder pb = new ProcessBuilder("cmd", "/c","C:\\apps\\vars.bat");
pb.command("C:\\apps\\test.exe","-u=user1", "-p=pwd1");
pb.redirectErrorStream(true);
pb.redirectOutput(outputFile);
Process process = pb.start();
try {
   process.waitFor();
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
   e.printStackTrace();
 }
 process.getOutputStream().close();
 InputStream is = process.getInputStream();
 BufferedReader in = new BufferedReader(new InputStreamReader(is));
 String inputLine;
 while ((inputLine = in.readLine()) != null) {
   System.out.println(inputLine);
 }

Below is vars.bat content

@rem Defined by Install. Please Do NOT Remove The Following Lines.
set VAR1=110002020150715
set DB_CONNECT=test
set DB_SERVER=localhost
set ORACLE_SID=test
set XML_ENCODING=ISO-8859-1

Problem is java program is not recognizing any of the environment variables set in .bat file.

vars.bat and test.exe both are from application installation location. For running test.exe first I need to run vars.bat because exe uses the variables set in .bat file to connect to application

Any idea, how to set the environment variables set in .bat file to process created using ProcessBuilder.

The ProcessBuilder is used to prepare a process to be started. The ProcessBuild will setup only one command to be executed. When you use command() it will set/change the command to be executed, so your previous command will be gone. Keep in mind that neither your "vars.bat" command nor your "test.exe" program has been executed yet. It will only be executed when you call the start() method, at which you can work with the returned Process object.

To run the "vars.bat" file before the "test.exe" file you have to create another "bat" file which will execute both commands. This way they will run in the same environment/shell/execution/container/process. So, create a new "bat" file with the following content:

vars.bat
test.exe -u=user1 -p=pwd1

Run this "bat" file with the installation directory as the start directory or use absolute paths to these files. Then you can run this new "bat" file with ProcessBuilder and Process like you already did before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM