为什么 Java Runtime.exec 命令有效但 ProcessBuilder 无法执行 Perforce 客户端命令?

Why is Java Runtime.exec command working but ProcessBuilder not able to execute the Perforce client command?

好的,要删除一个 Perfoce 标签,CommandLine 命令是:p4 label -d mylabel123。 现在我想使用 Java 执行此命令。我试过 Runtime.exec(),效果很好。但是,当我 运行 使用 ProcessBuilder 相同的命令时,它不起作用。任何帮助表示赞赏。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        exec1("p4 label -d mylabel123");
        exec2("p4","label -d mylabel123");
    }
    public static void exec1(String cmd)
            throws java.io.IOException, InterruptedException {
        System.out.println("Executing Runtime.exec()");
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(
                proc.getErrorStream()));

        String s = null;
        while ((s = stdInput.readLine()) != null) {
             System.out.println(s);
        }
        while ((s = stdError.readLine()) != null) {
             System.out.println(s);
        }
        proc.waitFor();
    }
    public static void exec2(String... cmd) throws IOException, InterruptedException{
        System.out.println("\n\nExecuting ProcessBuilder.start()");
        ProcessBuilder pb = new ProcessBuilder();
        pb.inheritIO();
        pb.command(cmd);
        Process process = pb.start();
        process.waitFor();
    }
}

方法 exec1() 输出:标签 mylabel123 已删除。

方法 exec2() 输出:未知命令。尝试 'p4 help' 获取信息。

ProcessBuilder 希望您提供命令名称和每个参数作为单独的字符串。当您(间接)执行

pb.command("p4", "label -d mylabel123");

您正在构建一个进程,运行s 使用单个参数 label -d mylabel123 命令 p4。您想要 运行 带有三个单独参数的命令:

pb.command("p4", "label", "-d", "mylabel123");

你的线索是第二种情况下的错误消息是由 p4 命令发出的(它说 "Try 'p4 help' for info")。很明显,问题出在论据上。不过,我承认 p4 确实通过将其参数之一称为 "command".

造成了一些混乱