It is simple to redirect all your stream to standard output using inheritIO() method. This will print the output to the stdout of the process from which you are running this command.

ProcessBuilder pb = new ProcessBuilder("command", "argument");
pb.directory(new File(<directory from where you want to run the command>));
pb.inheritIO();
Process p = pb.start();
p.waitFor();

There exist other methods too, like as mentioned below. These individual methods will help redirect only required stream.

    pb.redirectInput(Redirect.INHERIT)
    pb.redirectOutput(Redirect.INHERIT)
    pb.redirectError(Redirect.INHERIT)
Answer from Pandurang Patil on Stack Overflow
Top answer
1 of 12
188

Use ProcessBuilder.inheritIO, it sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.

CopyProcess p = new ProcessBuilder().inheritIO().command("command1").start();

If Java 7 is not an option

Copypublic static void main(String[] args) throws Exception {
    Process p = Runtime.getRuntime().exec("cmd /c dir");
    inheritIO(p.getInputStream(), System.out);
    inheritIO(p.getErrorStream(), System.err);

}

private static void inheritIO(final InputStream src, final PrintStream dest) {
    new Thread(new Runnable() {
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine()) {
                dest.println(sc.nextLine());
            }
        }
    }).start();
}

Threads will die automatically when subprocess finishes, because src will EOF.

2 of 12
74

For Java 7 and later, see Evgeniy Dorofeev's answer.

For Java 6 and earlier, create and use a StreamGobbler:

CopyStreamGobbler errorGobbler = 
  new StreamGobbler(p.getErrorStream(), "ERROR");

// any output?
StreamGobbler outputGobbler = 
  new StreamGobbler(p.getInputStream(), "OUTPUT");

// start gobblers
outputGobbler.start();
errorGobbler.start();

...

Copyprivate class StreamGobbler extends Thread {
    InputStream is;
    String type;

    private StreamGobbler(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    @Override
    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                System.out.println(type + "> " + line);
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › core › redirecting-output-process.html
Redirecting Output from a Process
October 20, 2025 - public static void redirectToFileTest() throws IOException, InterruptedException { File outFile = new File("out.tmp"); Process p = new ProcessBuilder("ls", "-la") .redirectOutput(outFile) .redirectError(Redirect.INHERIT) .start(); int status = p.waitFor(); if (status == 0) { p = new ProcessBuilder("cat" , outFile.toString()) .inheritIO() .start(); p.waitFor(); } } The excerpt redirects standard output to the file out.tmp.
🌐
Blogger
tamanmohamed.blogspot.com › 2012 › 06 › jdk7-processbuilder-and-how-redirecting.html
Improve your life Through Science and Art: JDK7: ProcessBuilder and how redirecting input and output from operating system's processes.
Create three new file instances to represent the three files involved in our process execution: input, output, and errors as follows: 2. Create the file Commands.txt using the path specified for the file and enter the following text: C: dir mkdir "Test Directory" dir3. Make sure that there is a carriage return after the last line. 4. Next, create a new instance of a ProcessBuilder, passing the string "cmd" to the constructor to specify the external process that we want to launch, which is the operating system command window. Call the redirectInput, redirectOutput, and redirectError methods with no arguments and print out the default locations: 5.
🌐
CodingTechRoom
codingtechroom.com › question › redirect-runtime-exec-output-in-java
How to Redirect Output of Runtime.getRuntime().exec() Using System.setOut() in Java? - CodingTechRoom
This process involves reading the input stream from the executed process and redirecting it appropriately. ... import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; class StreamGobbler extends Thread { private final InputStream inputStream; private final ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › ProcessBuilder.Redirect.html
ProcessBuilder.Redirect (Java Platform SE 7 )
Represents a source of subprocess input or a destination of subprocess output. Each Redirect instance is one of the following: ... Each of the above categories has an associated unique Type. ... Indicates that subprocess I/O will be connected to the current Java process over a pipe. This is the default handling of subprocess standard I/O. ... Indicates that subprocess I/O source or destination will be the same as those of the current process. This is the normal behavior of most operating system command interpreters (shells).
Find elsewhere
🌐
BCCNsoft
doc.bccnsoft.com › docs › jdk8u12-docs › api › java › lang › ProcessBuilder.html
ProcessBuilder (Java Platform SE 8 )
The argument may be null -- this means to use the working directory of the current Java process, usually the directory named by the system property user.dir, as the working directory of the child process. ... Sets this process builder's standard input source. Subprocesses subsequently started by this object's start() method obtain their standard input from this source. If the source is Redirect.PIPE (the initial value), then the standard input of a subprocess can be written to using the output stream returned by Process.getOutputStream().
🌐
Mysamplecode
mysamplecode.com › 2011 › 06 › java-redirect-systemout-to-file-console.html
Java redirect system.out to file - Programmers Sample Guide
I agree with that but sometimes the program is just a standalone process not part of a big application. And we want something quick and dirty for logging that info to a file. Add the following code to the beginning of the program call. PrintStream fileStream = new PrintStream(new FileOutputStream("myfile.txt",true)); //Redirecting console output to file (System.out.println) System.setOut(fileStream); //Redirecting runtime exceptions to file System.setErr(fileStream); Labels: Java ·
🌐
GeeksforGeeks
geeksforgeeks.org › java › redirecting-system-out-println-output-to-a-file-in-java
Redirecting System.out.println() Output to a File in Java - GeeksforGeeks
1 month ago - ... Note: PrintStream can be used for character output to a text file. Create a File object representing the target file. Create a PrintStream object using the file. Store the original System.out stream (optional but recommended).
Top answer
1 of 6
87

You can use the output stream redirector that is supported by the Windows command line, *nix shells , e.g.

java -jar myjar.jar > output.txt

Alternatively, as you are running the app from inside the vm, you could redirect System.out from within java itself. You can use the method

System.setOut(PrintStream ps)

Which replaces the standard output stream, so all subsequent calls to System.out go to the stream you specify. You could do this before running your wrapped application, e.g. calling System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));

If you are using a wrapper that you can't modify, then create your own wrapper. So you have FEST wrapper -> stream redirector wrapper -> tested app.

For example, you can implement a simple wrapper like this:

public class OutputRedirector
{
   /* args[0] - class to launch, args[1]/args[2] file to direct System.out/System.err to */
   public static void main(String[] args) throws Exception
   {  // error checking omitted for brevity
      System.setOut(outputFile(args(1));
      System.setErr(outputFile(args(2));
      Class app = Class.forName(args[0]);
      Method main = app.getDeclaredMethod("main", new Class[] { (new String[1]).getClass()});
      String[] appArgs = new String[args.length-3];
      System.arraycopy(args, 3, appArgs, 0, appArgs.length);
      main.invoke(null, appArgs);
   }
   protected PrintStream outputFile(String name) {
       return new PrintStream(new BufferedOutputStream(new FileOutputStream(name)), true);
   }
}

You invoke it with 3 additional params - the Main class to run, and the output/error directs.

2 of 6
54

When using this constructor:

new PrintStream(new BufferedOutputStream(new FileOutputStream("file.txt")));

remember to set autoflushing to true, i.e.:

new PrintStream(new BufferedOutputStream(new FileOutputStream("file.txt")), true);

otherwise you may get empty files even after your program finishes.

🌐
ZetCode
zetcode.com › java › processbuilder
Java ProcessBuilder - creating processes in Java
May 1, 2025 - RedirectErrorStream - Merges standard error output into standard output for streamlined handling. A program is executed with command. With waitFor we can wait for the process to finish. ... import java.io.IOException; void main() throws IOException, InterruptedException { var processBuilder = new ProcessBuilder(); processBuilder.command("notepad.exe"); var process = processBuilder.start(); var ret = process.waitFor(); System.out.printf("Program exited with code: %d", ret); }
🌐
Stack Overflow
stackoverflow.com › questions › 48985956 › redirect-process-output-to-a-stream
java - Redirect process output to a stream - Stack Overflow
February 26, 2018 - The output of the process is currently captured using a scanner. Process process = new ProcessBuilder(args).start(); Scanner scanner = new Scanner( (new InputStreamReader( process.getInputStream(), UTF_8_CHARSET))); Then the content captured from the scanner is redirected to a specific Console:
🌐
CodingTechRoom
codingtechroom.com › question › redirect-system-out-system-err-java
How to Redirect System.out and System.err in Java - CodingTechRoom
// Redirecting System.out and System.err to files try { PrintStream out = new PrintStream(new FileOutputStream("output.txt")); System.setOut(out); PrintStream err = new PrintStream(new FileOutputStream("errors.txt")); System.setErr(err); } catch (FileNotFoundException e) { e.printStackTrace(); }
🌐
Java2s
java2s.com › example › java-api › java › lang › processbuilder › redirectoutput-1-3.html
Example usage for java.lang ProcessBuilder redirectOutput
public void run() { try {//from w w w . j a v a 2s. c o m clientSock = new Socket(ioServer, ioServerPort); System.setOut(new PrintStream(clientSock.getOutputStream(), true)); System.setErr(new PrintStream(clientSock.getOutputStream(), true)); String hostName = InetAddress.getLocalHost().getHostName(); System.out.println("Starting process " + executable + " on " + hostName); List<String> commands = new ArrayList<String>(); commands.add(executable); if (appArgs != null && appArgs.length > 0) { commands.addAll(Arrays.asList(appArgs)); } ProcessBuilder processBuilder = new ProcessBuilder(commands)
🌐
Whitfin
whitfin.io › blog › redirecting-inputstream-outputstream-java
Whitfin's Blog: Redirecting An InputStream To An OutputStream In Java
If you didn't care about waiting for the completion, you can skip the call to .join() which would then continue to processing with no knowledge of if the file had finished downloading. Below is another example, this time redirecting STDERR to STDOUT (this is a messy example but it gets the point across). package io.whitfin.javatest; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; public class MainTest { public static void main(String[] args) throws InterruptedException, IOException { // Create an InputStream variable based on System.in InputStream is