5

I am trying to execute .bat file using java process builder but it does not starts the process. Please tell me what i am doing wrong here. This code works fine with linux envoirnment when I replace file.bat with ./file.sh

final ArrayList<String> command = new ArrayList<String>();
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
    builder.redirectErrorStream(true);
    builder.start();
    } catch (IOException e) {
      logger.error("Could not start process." ,e);
} 
7
  • can you post the value of the WORKING_DIR variable? Commented Jun 15, 2013 at 6:18
  • using java property to get the current working directory System.getProperty("user.dir") Commented Jun 15, 2013 at 6:19
  • 1
    try to use Runtime Class, here is an example, it will work well, docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html Commented Jun 15, 2013 at 6:20
  • Which commands are you using in file.bat ? Commented Jun 15, 2013 at 6:27
  • java -jar netx.jar ..... Commented Jun 15, 2013 at 6:48

2 Answers 2

9

First element in array must be an executable. So you have to invoke cmd.exe in order to call you batch file.

ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", WORKING_DIR + File.separator + "file.bat"}));
Sign up to request clarification or add additional context in comments.

2 Comments

still the same problem. it doesn't start the new process and kills the existing one
You don't have to invoke cmd.exe. A .bat file can be executed. I just wrote a small test case: import java.io.IOException; class Test { public static void main(String args[]) throws InterruptedException, IOException { ProcessBuilder processBuilder = new ProcessBuilder(args[0]); processBuilder.inheritIO(); Process process = processBuilder.start(); process.waitFor(); } }. I have a foo.bat: echo "Hello, world". Then I do java Test foo.bat
1

Make sure the path to the bat file is correct. You can either debug it using a debugger or put a sysout to determine that:

final ArrayList<String> command = new ArrayList<String>();
System.out.println("Batch file path : " + WORKING_DIR+File.separator+"file.bat")
command.add(WORKING_DIR+File.separator+"file.bat");
final ProcessBuilder builder = new ProcessBuilder(command);
try {
    builder.redirectErrorStream(true);
    builder.start();
    } catch (IOException e) {
      logger.error("Could not start process." ,e);
} 

Comments

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.