Java System redirect System.out stream

Description

Java System redirect System.out stream

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Main {
  public static void main(String[] args) throws Exception {
    File outFile = new File("stdout.txt");
    PrintStream ps = new PrintStream(new FileOutputStream(outFile));

    // Print a message on console
    System.out.println("Messages will be redirected to " + outFile.getAbsolutePath());

    // Set the standard out to the file
    System.setOut(ps);// w w  w. jav a 2  s.  com

    // The following messages will be sent to the stdout.txt file
    // Your would see the message on screen.
    System.out.println("Hello world!");
    System.out.println("demo2s.com");
  }
}



PreviousNext

Related