[英]Why is Java Runtime.exec command working but ProcessBuilder not able to execute the Perforce client command?
好的,因此要刪除Perfoce Label,請使用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幫助”以獲取信息。
ProcessBuilder
希望您提供命令名稱和每個參數作為單獨的字符串。 當您(間接)執行
pb.command("p4", "label -d mylabel123");
您正在構建一個運行帶有單個參數label -d mylabel123
命令p4
的進程。 您想使用三個單獨的參數運行該命令:
pb.command("p4", "label", "-d", "mylabel123");
您的線索可能是第二種情況下的錯誤消息是由p4
命令發出的(它說“為信息嘗試'p4 help'”)。 顯然,問題出在參數上。 不過,我承認, p4
確實通過將其參數之一稱為“命令”而造成了一些混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.