[英]Why is Java Runtime.exec command working but ProcessBuilder not able to execute the Perforce client command?
Ok, so to delete a Perfoce Label , the CommandLine command is: p4 label -d mylabel123
. 好的,因此要删除Perfoce Label,请使用CommandLine命令:
p4 label -d mylabel123
。 Now I want to execute this command using Java. 现在,我想使用Java执行此命令。 I tried
Runtime.exec()
and it works like charm. 我试过
Runtime.exec()
,它就像魅力。 However when I run the same command using ProcessBuilder
it doesn't work. 但是,当我使用
ProcessBuilder
运行相同的命令时,它不起作用。 Any help appreciated. 任何帮助表示赞赏。
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();
}
}
Method exec1() output: Label mylabel123 deleted. 方法exec1()输出: 删除标签mylabel123。
Method exec2() output: Unknown command. 方法exec2()输出: 未知命令。 Try 'p4 help' for info.
尝试“ p4帮助”以获取信息。
ProcessBuilder
wants you to provide the command name and each argument as separate strings. ProcessBuilder
希望您提供命令名称和每个参数作为单独的字符串。 When you (indirectly) perform 当您(间接)执行
pb.command("p4", "label -d mylabel123");
you are building a process that runs command p4
with a single argument, label -d mylabel123
. 您正在构建一个运行带有单个参数
label -d mylabel123
命令p4
的进程。 You want instead to run that command with three separate arguments: 您想使用三个单独的参数运行该命令:
pb.command("p4", "label", "-d", "mylabel123");
Your clue would have been that the error message in the second case is emitted by the p4
command (it says "Try 'p4 help' for info"). 您的线索可能是第二种情况下的错误消息是由
p4
命令发出的(它说“为信息尝试'p4 help'”)。 Clearly, then, the problem is with the arguments. 显然,问题出在参数上。 I grant you, though, that
p4
does create some confusion by calling one of its arguments a "command". 不过,我承认,
p4
确实通过将其参数之一称为“命令”而造成了一些混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.