从 Java 代码运行批处理文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19103570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:07:33  来源:igfitidea点击:

Run batch file from Java code

javabatch-file

提问by Ricardo

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

我正在尝试从我的 Java 可执行文件运行另一个目录中的批处理文件。我有以下代码:

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

The result is that the program opens a cmd window in the root directory where the program was run at and doesn't access the file path I provided.

结果是程序在运行程序的根目录中打开了一个 cmd 窗口,并且没有访问我提供的文件路径。

采纳答案by rob

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

而不是Runtime.exec(String command),您需要使用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'd use ProcessBuilderinstead, which is a little more verbose but much easier to use and debug than Runtime.exec().

但就我个人而言,我会ProcessBuilder改用它,它比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();

回答by dev2d

try following

尝试跟随

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

回答by kdureidy

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.

您必须显示 bat 文件的内容,您的问题出在 bat 文件内的路径中。

回答by Amit Kumar

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.

这对您有用并且易于使用。

回答by Krunal Chauhan

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();