2017-07-18 49 views
0

我正在開發一個用於intelliJ的插件。無法使用java進程運行mvn

我需要在我的java代碼中調用一些mvn命令。但奇怪的是,它返回我一個IOexception

Cannot run program "mvn" (in directory "/Users/ryouyasachi/Getty/semantiful-differentials-getty/getty/dsproj"): 
error=2, No such file or directory 

這是我的代碼:

/** @return: null if the process does not exit with 0 
* @return: output if the process exits with 0 
*/ 

public static String runCommand(String directory, List<String> command) { 

    ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File(directory)); 

    processBuilder.redirectErrorStream(true); 

    Process process; 
    String output = null; 
    try { 
     process = processBuilder.start(); 


     //Pause the current thread until the process is done 
     process.waitFor(); 

     //When the process does not exit properly 
     if (process.exitValue() != 0) { 

      //Error 
      System.out.println("command exited in error: " + process.exitValue()); 

      //Handle the error 
      return null; 
     }else { 

      output = readOutput(process); 
      System.out.println(output); 
     } 

    } catch (InterruptedException e) { 
     System.out.println("Something wrong with command: " +e.getMessage()); 

    } catch (IOException e) { 
     System.out.println("Something wrong with command: " +e.getMessage()); 
    } 

    return output; 
} 

/** 
* 
* @param process which exits with 0 
* @return The output string of the process 
*/ 
private static String readOutput(Process process){ 
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); 


    String line; 
    StringBuilder stringBuilder = new StringBuilder(); 
    try { 

     while ((line = in.readLine()) != null) { 
      stringBuilder.append(line); 
     } 

     in.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return stringBuilder.toString(); 
} 

PS: 1.我能夠運行我需要提示的項目目錄下的MVN指令這應該表明項目目錄確實存在,並且我已經正確安裝了maven。

2.我的代碼與git命令運行正常。

+0

'沒有這樣的文件或目錄'是非常明確的。它找不到'mvn'可執行文件。路徑設置是否正確? –

+0

我這麼認爲。我能夠在沙箱裏智能IDEA中運行mvn。 'JAVA_HOME JAVA_HOME = /圖書館/的Java/JavaVirtualMachines/jdk1.8.0_131.jdk /內容/首頁 出口JAVA_HOME M2_HOME = /用戶/ ryouyasachi/Apache的行家-3.5.0 出口M2_HOME PATH = $路徑:$ JAVA_HOME/bin:$ M2_HOME/bin 導出PATH'在我的.bash_profile –

回答

1

您是否考慮過使用Maven Invoker而不是訴諸於系統調用?

調用程序會自動嘗試通過 檢測Maven安裝評估系統屬性maven.home和環境變量 M2_HOME

他們沒有說什麼PATH所以我不確定是否處理了您的特定問題,但您的大部分代碼都是由開箱即用的調用者提供的樣板文件。

0

即使mvn在您的PATH,this answer說明new ProcessBuilder第一個參數必須是可執行文件的完整路徑調用。

因此,請嘗試傳遞mvn的完整路徑作爲第一個參數(其他參數是mvn的參數,如果有的話)。