Run batch file from Java code

后端 未结 5 1315
南旧
南旧 2020-11-30 06:56

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

    try {
        Process p =  Runtime.getR         


        
相关标签:
5条回答
  • 2020-11-30 07:26

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

    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'd use ProcessBuilder instead, which is a little 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();
    
    0 讨论(0)
  • 2020-11-30 07:27

    try following

    try {
                String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
                Process p =  Runtime.getRuntime().exec(command);           
            } catch (IOException ex) {
            }
    
    0 讨论(0)
  • 2020-11-30 07:44

    Following is worked 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();
    
    0 讨论(0)
  • 2020-11-30 07:46
    import java.lang.Runtime;
    
    Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");
    

    This will work for you and is easy to use.

    0 讨论(0)
  • 2020-11-30 07:49

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

    You have to show the content of the bat file, your problem is in the paths inside the bat file.

    0 讨论(0)
提交回复
热议问题