代码运行批处理文件

代码运行批处理文件

本文介绍了从 Java 代码运行批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.getRuntime().exec("cmd /c start "C:\Program Files\salesforce.com\Data Loader\cliq_process\upsert\upsert.bat"") ;
    } catch (IOException ex) {
    }

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

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.

推荐答案

而不是Runtime.exec(String command),你需要使用exec(String command, String[]envp, File dir) 方法签名:

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

但就我个人而言,我会改用 ProcessBuilder,它比 Runtime.exec() 更冗长但更易于使用和调试.

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

这篇关于从 Java 代码运行批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 07:58