Run batch file from Java code

I am trying to run a batch file that is in a different directory from a Java executable. I have the following code:

try { Process p = Runtime.getRuntime().exec("cmd /c start \"C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert\\upsert.bat\"") ; } catch (IOException ex) { } 

As a result, the program opens the cmd window in the root directory where the program was launched, and does not gain access to the specified file path.

+6
source share
5 answers

Instead of Runtime.exec(String command) you need to use the signature of the exec(String command, String[] envp, File dir) method exec(String command, String[] envp, File dir) :

 Process p = Runtime.getRuntime().exec("cmd /c upsert.bat", null, new File("C:\\Program Files\\salesforce.com\\Data Loader\\cliq_process\\upsert")); 

But personally, I would use ProcessBuilder instead, which is a bit more verbose, but much easier to use and debug than Runtime.exec() .

 ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "upsert.bat"); File dir = new File("C:/Program Files/salesforce.com/Data Loader/cliq_process/upsert"); pb.directory(dir); Process p = pb.start(); 
+21
source

try to execute

 try { String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"}; Process p = Runtime.getRuntime().exec(command); } catch (IOException ex) { } 
+6
source

Your code is fine, but the problem is inside the batch file.

You should show the contents of the bat file, your problem is in the paths inside the bat file.

+2
source

The following works for me

 File dir = new File("E:\\test"); ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat"); pb.directory(dir); Process p = pb.start(); 
+1
source
 import java.lang.Runtime; Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file"); 

It will work for you and is easy to use.

0
source

Source: https://habr.com/ru/post/954974/


All Articles