无法用java进程运行mvn

时间:2017-07-18 04:45:04

标签: java maven intellij-idea

我正在为intelliJ开发一个插件。

我需要在我的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命令正常运行。

2 个答案:

答案 0 :(得分:1)

您是否考虑过使用Maven Invoker而不是诉诸系统调用?

  

Invoker将自动尝试通过检测Maven安装   评估系统属性maven.home和环境变量   M2_HOME

他们没有对PATH说些什么,所以我不确定你的特定问题是否得到处理,但你的大部分代码都是样板,由调用者提供开箱即用。

答案 1 :(得分:0)

即使mvn中有PATHthis answer也说明new ProcessBuilder第一个参数必须是被称为可执行文件的完整路径。

所以尝试将mvn的完整路径作为第一个参数传递(其他参数是mvn的参数,如果有的话)。

相关问题