开发者

ant java task : redirecting output with spawn=true

Greetings,

a rather clear question here.

I have to launch a java job with <java>, which is to be run in parallel with ant and开发者_如何学Python it's okay if the job outlives the ant process, hence spawn="true".

I have to see the job output in a designated file. This is perfectly achievable via output="job.out" for spawn="false", but I am kinda out of luck having spawn"=true".

So, is there any modestly dirty hack or I really have to wrap the java call with an exec like the one below?

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

Thanks, Anton


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜