2015-11-23 22 views
1

工作,我試圖從使用zenity命令的用戶輸入。下面是我傳遞給zenity命令:Zenity bash命令不使用Java

zenity --question --title "Share File" --text "Do you want to share file?" 

下面是一個使用Java來執行命令的代碼:

private String[] execute_command_shell(String command) 
{ 
    System.out.println("Command: "+command); 
    StringBuffer op = new StringBuffer(); 
    String out[] = new String[2]; 
    Process process; 
    try 
    { 
     process = Runtime.getRuntime().exec(command); 
     process.waitFor(); 
     int exitStatus = process.exitValue(); 
     out[0] = ""+exitStatus; 
     BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
     String line = ""; 
     while ((line = reader.readLine()) != null) 
     { 
      op.append(line + "\n"); 
     } 
     out[1] = op.toString(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return out; 
} 

雖然我得到的輸出對話框,標題只有第一單詞「共享」,問題的文本還顯示只有一個字「做」

是否有任何解釋這個奇怪的行爲呢?什麼是工作?

+0

你必須在命令字符串變量正確的報價? –

+0

@EtanReisner在上面提到的zenity命令是execute_command_shell方法的第一行的輸出 – gonephishing

+0

你剝奪'命令:'關閉它呢?好。聽起來像某些東西不是通常將命令解析爲shell命令。 WillShackleford的回答涵蓋了(儘管笨拙地)使用一系列參數來代替。這可能是最好的答案。 –

回答

1

這爲我工作:

Runtime.getRuntime().exec(new String[]{"zenity","--question","--title","Share File","--text","Do you want to share file?"}) 

我會建議在Java代碼分裂參數,以便您可以檢查,而不是傳遞整個命令用引號。

這裏是包括分割處理引號的例子:

String str = "zenity --question --title \"Share File\" --text \"Do you want to share file?\""; 
String quote_unquote[] = str.split("\""); 
System.out.println("quote_unquote = " + Arrays.toString(quote_unquote)); 
List<String> l = new ArrayList<>(); 
for(int i =0; i < quote_unquote.length; i++) { 
    if(i%2 ==0) { 
     l.addAll(Arrays.asList(quote_unquote[i].split("[ ]+"))); 
    }else { 
     l.add(quote_unquote[i]); 
    } 
} 
String cmdarray[] = l.toArray(new String[l.size()]); 
System.out.println("cmdarray = " + Arrays.toString(cmdarray)); 
Runtime.getRuntime().exec(cmdarray); 
+0

分裂成命令的參數數組爲我工作:)但是你可以請解釋爲什麼會發生這樣的嗎? – gonephishing

+0

我不確定自己瞭解細節。但據我瞭解,當你運行一個shell時,shell將參數句柄加引號的塊等分割,而zeniity程序獲得已經分割的參數。在這裏,我們繞過了shell並將命令更直接地傳遞給操作系統,該操作系統不會像shell那樣處理引號。 – WillShackleford