[英]Execute cmd script with double quotes
我試圖用多個參數執行一個Process
,但它們有雙引號"..."
。
這是我構建腳本的方式:
public void capture(String from, String to, String outputFile)
此方法將運行該命令,它采用此處給出的3個參數:
capture("0", "100", "C:\\\\Program Files\\\\myProgram\\\\file.txt")
所以完整的構建命令如下所示:
String command = "\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis "
+ from + " " + to + " \"" + outputFile + "\"";
要清楚地看到它,這是命令的可視輸出:
"C:\\Program Files (x86)\\otherProg\\prog.exe" /dothis 0 100 "C:\\Program Files\\myProgram\\file.txt"
好的,然后我執行它:
String[] script = {"cmd.exe", "/c", command};
Process p = Runtime.getRuntime().exec(script);
在這一點上沒有任何反應。
命令沒有執行, 但是如果我接受輸出:
"C:\\Program Files (x86)\\otherProg\\prog.exe" /dothis 0 100 "C:\\Program Files\\myProgram\\file.txt"
將它復制粘貼到CMD命令DOES執行(我得到預期的輸出)。
我試過像這樣構建命令,但同樣的效果發生了。
運行該命令的唯一可能方法是這樣做:
"C:\\Program Files (x86)\\otherProg\\prog.exe" /dothis 0 100 C:\\Folder\\myProgram\\file.txt
沒有最后一個參數的引號,當然,路線中沒有空格 。
這是什么解決方案?
更新1:
還嘗試了script = script.replace("\\n","").replace("\\t","")
並且都script = script.replace("\\n","").replace("\\t","")
。
更新2:
剛嘗試構建這樣的過程:
Process p = Runtime.getRuntime().exec(
"\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis 0 100 \"C:\\Program Files\\myProgram\\file.txt\"");
將轉義命令直接傳遞給進程確實有效,但是為什么它們在參數和構建字符串時不起作用?
在下面向Tim Biegeleisen致謝
正如他所提到的,java存在一個問題,即命令和參數之間的區別以及何時運行多個命令,要解決此問題,請執行下一步:
String command = "cd \"C:\\Program Files (x86)\\otherProgram\\\" & program.exe /capture "+from+" "+to+" \""+outputFile+"\"";
&
它的工作原理。
我發布這個主要是為了提供信息。 請考慮以下代碼:
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe echo Hello World");
這確實會導致命令提示符出現在我的主目錄(默認)目錄中,但它實際上不會執行echo
命令。 實際上,以下內容也是如此:
Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe blah blah blah");
因此,似乎Java忽略了cmd.exe
之后的所有內容。 我對此的解釋是實際命令是start
,該命令的參數是cmd.exe
。 換句話說,一旦Java啟動了命令提示符,它就已經使用了該參數,其他一切都被忽略了。
這一觀察結果與您的發現一致,即以下工作:
Process p = Runtime.getRuntime().exec(
"\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis 0 100 \"C:\\Program Files\\myProgram\\file.txt\"");
在這種情況下,命令是prog.exe
,后面的內容是參數。 但是,如果您嘗試將命令傳遞到命令提示符並從那里運行,則它將無法工作。
因此,似乎使用Runtime.getRuntime().exec()
允許您從Java執行一個進程,但不能執行其中兩個進程。 這是有道理的,因為Java可以執行一個進程,但API不允許它從第一個進程啟動第二個進程。
嘗試使用流程構建器和/或分離您的參數
Process Builder
ProcessBuilder pb = new ProcessBuilder("\"C:\\Program Files (x86)\\otherProg\\prog.exe\"", "/dothis ", "from + " " + to + " \"" + outputFile + "\"");
Process p = pb.start();
運行
Runtime.getRuntime().exec(new String[]{"\"C:\\Program Files (x86)\\otherProg\\prog.exe\"", "/dothis ", "from + " " + to + " \"" + outputFile + "\""});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.