dontholdthelittlefella
dontholdthelittlefella

Reputation: 101

Is it possible to redirectOutput of ProcessBuilder to more than one file?

I want to redirect the output of the ProcessBuilder to more than one file.

It is possible to redirect the output to only one file with:

new ProcessBuilder().redirectOutput(Redirect.appendTo(outputFile));

I tried to do:

new ProcessBuilder().redirectOutput(Redirect.appendTo(outputFile))
                    .redirectOutput(Redirect.appendTo(outputFile2));

But it only writes to the second file.

How can I write the same output to more than one file?

Upvotes: 2

Views: 3169

Answers (1)

John Bollinger
John Bollinger

Reputation: 180113

The redirectOutput(ProcessBuilder.Redirect) method of ProcessBuilder sets a property of the builder. If you invoke it again then it sets that property again, with the new value you specify. You cannot duplicate the output this way, in part because ProcessBuilder just doesn't work that way, but also because the Process it's building has only one output stream that could be redirected to begin with.

You have several options, among them:

  • Redirect to a single file, and copy the file afterward.
  • Redirect the output back to your Java program (Redirect.PIPE, which is the default). Then have your program read the process's output and write it to the two target files. If the process is meant to be asynchronous with respect to Java then you'd want to set up the Java-side stream splitting to run its own thread.
  • If your operating environment has a command that will help you, such as UNIX tee, then you may be able to adjust the command the process runs so that it creates one copy of the output itself. For example,

    new ProcessBuilder().command("bash", "-c", "mycommand --option | tee output1")
            .redirectOutput(Redirect.appendTo(outputFile2));
    

Of those, the second is the only one that is handled entirely by Java and is independent of the operating environment. If it is suitable for your case, however, the third is probably the easiest to get running.

Upvotes: 5

Related Questions