2017-08-08 112 views
0

我想使用Java和ProcessBuilder運行腳本。當我嘗試運行時,我收到以下消息:錯誤= 2,沒有這樣的文件或目錄。使用ProcessBuilder運行shell腳本

我不知道我做錯了,但這裏是我的代碼(PS:我試着不帶參數只執行腳本和錯誤是一樣的:

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""}; 
ProcessBuilder p = new ProcessBuilder(command); 

    try { 

     // create a process builder to send a command and a argument 
     Process p2 = p.start(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(p2.getInputStream())); 
     String line; 

     log.info("Output of running " + command + " is: "); 
     System.out.println("Output of running " + command + " is: "); 
     while ((line = br.readLine()) != null) { 
      log.info(line); 
     } 

    } 
+0

的([的ProcessBuilder和的Runtime.exec()之間的不同]可能的複製https://stackoverflow.com/questions/6856028/process-process-and-runtime-exec之間的差異) – Steephen

回答

0

嘗試更換

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""}; 

String[] command = {"/teste/teste_back/script.sh", argument1, argument}; 

參考ProcessBuilder以獲取更多信息。

的ProcessBuilder(字符串...命令)

構造一個進程生成具有指定操作系統 程序和參數。

+0

實際上,問題在於我的字符串的最後一個引用以及參數。 – Alvp

+0

@Alvp - 在我的回答中沒有正確解決嗎? – Beginner

+0

是的,它是正確的。 – Alvp

0

除非你script.sh其名稱中有一個逗號,這是錯誤的:

String[] command = {"/teste/teste_back/script.sh" , argument1, argument}; 
0

您可以定義的ProcessBuilder的方法。

public static Map execCommand(String... str) { 
    Map<Integer, String> map = new HashMap<>(); 
    ProcessBuilder pb = new ProcessBuilder(str); 
    pb.redirectErrorStream(true); 
    Process process = null; 
    try { 
     process = pb.start(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    BufferedReader reader = null; 
    if (process != null) { 
     reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
    } 

    String line; 
    StringBuilder stringBuilder = new StringBuilder(); 
    try { 
     if (reader != null) { 
      while ((line = reader.readLine()) != null) { 
       stringBuilder.append(line).append("\n"); 
      } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     if (process != null) { 
      process.waitFor(); 
     } 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 

    if (process != null) { 
     map.put(0, String.valueOf(process.exitValue())); 
    } 

    try { 
     map.put(1, stringBuilder.toString()); 
    } catch (StringIndexOutOfBoundsException e) { 
     if (stringBuilder.toString().length() == 0) { 
      return map; 
     } 
    } 
    return map; 
} 

你可以調用函數來執行shell命令或腳本

String cmds = "ifconfig"; 
String[] callCmd = {"/bin/bash", "-c", cmds}; 
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString()); 
System.out.println(); 
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());