ant java task:使用spawn = true重定向输出

问候,

这是一个相当明确的问题.

我必须使用< java>启动一个java作业,它将与ant并行运行,如果作业比ant进程更长,则可以,因此spawn =“true”.

我必须在指定的文件中看到作业输出.对于spawn =“false”,这可以通过output =“job.out”完全实现,但是我有点运气产生“= true”.

那么,有没有任何适度的黑客攻击或我真的必须用下面的exec包装java调用?

CMD /C my-java-command-and-hardcoded-classpath-goes-here > job.out

谢谢,
安东

最佳答案

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class StreamRedirector {
    public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException,
            NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        System.out.println(Arrays.toString(args));
        //  parse the arguments
        if (args.length != 2) {
            throw new IllegalArgumentException(
                    "Usage:" +
                        "\targ0 = wrapped main FQN;\n" +
                        "\targ1 = dest output file name;\n" +
                        "\tother args are passed to wrapped main;"
            );
        }
        String mainClass = args[0];
        String destinationFile = args[1];

        //  redirect the streams
        PrintStream outErr = new PrintStream(new FileOutputStream(destinationFile));
        System.setErr(outErr);
        System.setOut(outErr);

        //  delegate to the other main
        String[] wrappedArgs = new String[args.length - 2];
        System.arraycopy(args, 2, wrappedArgs, 0, wrappedArgs.length);
        Class.forName(mainClass).getMethod("main", String[].class).invoke(null, (Object) wrappedArgs);
    }
}
点赞