Anton Kraievyi
Anton Kraievyi

Reputation: 4342

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 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

Upvotes: 4

Views: 3142

Answers (1)

Anton Kraievyi
Anton Kraievyi

Reputation: 4342

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

Upvotes: 3

Related Questions