The Out,error in system are final type and cannot be changed. However, the new output stream can be set through SetOut (), thus enabling the ability to write logs.
Import Java.io.PrintStream; Import java.io.FileNotFoundException; public class Redirectoutputstream {public static void Main (String arg[]) { try{ printstream out = System.out ; Keep the original output stream printstream ps = new PrintStream ("./log.txt");//create file output stream system.setout (PS);//set use new output stream int age = ; SYSTEM.OUT.PRINTLN ("Age variable success definition, initial value is:"); String sex = "female"; SYSTEM.OUT.PRINTLN ("Gender variable success definition, initial value: female"); String info = "This is" + Sex + "child, should have" +age+ "age"; System.out.println ("consolidates two variables as info string variable, the result is" +info "); System.setout (out); Restore the original output stream System.out.println ("The program has finished running, please review the log file. "); } catch (FileNotFoundException e) { e.printstacktrace ();}
The logs are as follows:
Age variable successfully defined, initial value is: 18
The gender variable was successfully defined, and the initial value was: female
Consolidates two variables for the info string variable, the result is that this is a girl and should be 18 years old
Summarize:
The method holds the out member variable of the system class as a temporary variable, then creates a new file output stream and sets the output stream to the new output stream of the system class. and the continuous debugging information is output to the log. Main methods:
1. SetOut () method: Reassign the standard output stream of the system class.
2. Seterr () method: Reassign the standard error output stream of the system class.
3. SetIn () method: Reassign the standard input stream of the system class.