0

I have a folder named A that contains a .bat file: a.bat. If I wanted to write a .bat file I could write:

cd A/
call a.bat

and I would see the results, but if I want to run it from Java I have problems.

I'm trying to do this:

String command = "cmd.exe /c start cd A/\ncall a.bat";
try {
    Runtime.getRuntime().exec(command); 
} catch (IOException e) { }

I tried to replace \n with ; and with \r and with && but that didn't work. (It doesn't recognize that there exist two lines).

How can I run multiple lines from a .bat from Java?

Maroun
  • 94,125
  • 30
  • 188
  • 241

1 Answers1

1

You can set the working directory for the process from the Java side at the point where you spawn cmd, rather than needing a cd command:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "a.bat");
pb.directory(new File("path\\to\\A"));
Process p = pb.start(); 
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • Is there a way to actually open the `CMD` window to see the results? – Maroun Feb 28 '13 at 11:22
  • @MarounMaroun maybe by using `start`, i.e. `new ProcessBuilder("cmd.exe", "/c", "start", "a.bat")`? I'm not a Windows user so I don't know for sure. – Ian Roberts Feb 28 '13 at 11:30