运行 来自 Java 使用运行时的 maven 命令

Running maven command from Java using Runtime

我正在尝试从 java main 执行 运行 maven 命令,但它对我来说并不如我所愿。

当我 运行 下面的代码 运行 是这个主要 class 所在的同一个现有项目上的 maven 命令,但我想 运行此 Maven 命令从 class 到任何其他项目文件夹。

请帮忙!

提前致谢!

package com.codecoverage.runner;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class MavenCoberturaRunner {

    public static void main(String[] args) throws IOException, InterruptedException {

         Process p = null;

            try {
                p = Runtime.getRuntime().exec("C:/apache-maven-2.0.9/apache-maven-2.0.9/bin/mvn.bat clean cobertura:cobertura -Dcobertura.report.format=xml");
            } catch (IOException e) {
                System.err.println("Error on exec() method");
                e.printStackTrace();
            }

            copy(p.getInputStream(), System.out);
            p.waitFor();

        }

        static void copy(InputStream in, OutputStream out) throws IOException {
            while (true) {
                int c = in.read();
                if (c == -1)
                    break;
                out.write((char) c);
            }
        }
        }

在命令行中使用-f

C:/apache-maven-2.0.9/apache-maven-2.0.9/bin/mvn.bat -f path/to/your/pom.xml 干净cobertura:cobertura -Dcobertura.report.format=xml

你应该使用Runtime.exec(String command, String[] envp, File dir)方法, 它在具有指定环境和工作目录的单独进程中执行指定的字符串命令。

您想要的是设置工作目录,使其指向您需要 运行 Maven 所在的位置。