gpt4 book ai didi

java - 无法使用java进程运行mvn

转载 作者:行者123 更新时间:2023-12-02 12:35:48 26 4
gpt4 key购买 nike

我正在开发一个 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 命令运行良好。

最佳答案

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

The Invoker will automatically try to detect a Maven installation by evaluating the system property maven.home and the environment variable M2_HOME

他们没有提及任何有关 PATH 的内容,因此我不确定您的特定问题是否已得到处理,但您的大部分代码都是由调用者开箱即用提供的样板文件。

关于java - 无法使用java进程运行mvn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com