2015-10-07 63 views
0

我正在運行使用Java的命令並且沒有輸出。使用Java運行Linux命令時出現問題?

Process p; 
Runtime run = Runtime.getRuntime(); 
    String s1 = "queryData 1005017 --format '\"%s" scope'"; 

    System.out.println("Command is " + s1); 


    try { 

     p = run.exec(s1); 
     BufferedReader br = new BufferedReader(
       new InputStreamReader(p.getInputStream())); 
      while ((s = br.readLine()) != null) 
       System.out.println("line: " + s); 
     p.getErrorStream(); 
     p.waitFor(); 

    } 

while the command ---> queryData 1005017 --format''%s「scope'runs without any issue。想知道是否在處理雙引號或%符號時丟失了任何內容?

+1

假設你丟失的反斜槓只是一個錯字(?沒有你的程序編譯),你嘗試過檢查'p.exitValue()'了'waitFor'後,看它是否終止成功或沒有? – RealSkeptic

+0

是的,這是錯字。我得到的退出值是退出:1 – Ammad

+0

因此退出失敗。嘗試閱讀錯誤流而不是輸入流,看看它給你帶來了什麼樣的錯誤。 – RealSkeptic

回答

2

請不要使用字符串從Java啓動進程。正確的方法是使用ProcessBuilder

p = new ProcessBuilder(Arrays.asList(
    "queryData", "1005017", "--format", "\"%s\" scope")).start(); 
+0

謝謝。解決這個問題。 – Ammad

2

你沒有正確轉義內部引號:

String s1 = "queryData 1005017 --format '\"%s" scope'"; 
      ^--start java string    ^--end java string 
               ^^^^^ what's this mean to java? 

你可能想

String s1 = "queryData 1005017 --format '\"%s\" scope'"; 
              ^--note this 

代替。

+2

那麼,這不會編譯,OP說它不會返回輸出。也許這只是一個錯字。 – RealSkeptic

+0

是的,這是排字錯誤 – Ammad