如何通过Java的Main方法执行gradle构建命令

umuewwlo  于 2023-03-03  发布在  Java
关注(0)|答案(2)|浏览(216)

我正在尝试通过Java类的main方法执行gradle build命令(使用cmd提示符)。

public class GradleScriptEditor {

    public static void main(String[] args) throws IOException {
        String command_to_be_executed = "gradle build";
        String directory_location = "C:\\mycode\\ws";

        String[] command = {command_to_be_executed};
        ProcessBuilder builder = new ProcessBuilder(command);
        builder = builder.directory(new File(directory_location));

        Process p = builder.start();
        OutputStream outputStream = new FileOutputStream(new File(directory_location+ "/mylog.log"));
        outputStream.write(p.getInputStream().readAllBytes());
        outputStream.close();
    }
}

但我得到了以下错误:

Exception in thread "main" java.io.IOException: Cannot run program "gradle build" (in directory "C:\\mycode\\ws"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1143)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1073)
    at practice.GradleScriptEditor.main(GradleScriptEditor.java:16)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:499)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:158)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1110)
    ... 2 more

Process finished with exit code 1

请注意,当我使用ipconfig测试我的代码时,它工作正常。
请告诉我如何解决这个问题。

ocebsuys

ocebsuys1#

根据文件public ProcessBuilder(String... command)
使用指定的操作系统程序和参数构造流程构建器。这是一个方便的构造函数,它将流程构建器的命令设置为字符串列表,该列表包含与命令数组相同的字符串,顺序相同
这意味着您需要将命令传递为

String[] command = {"gradle", "build"};
qjp7pelc

qjp7pelc2#

不要启动流程,而是使用Gradle工具API。此处无法教您如何使用工具API,但我会留下几个链接供您浏览。
https://www.sobyte.net/post/2022-02/gradle-tooling-api/
https://gist.github.com/buzztaiki/2046728

相关问题