This article mainly introduces how to record program logs with files for the Al output stream in Java. This article provides code examples and provides detailed annotations for the code, for more information, see out and error in System. They are of the final type and cannot be modified. However, you can set a new output stream through setOut () 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; // retain the original output stream PrintStream ps = new PrintStream (". /log.txt "); // create the file output stream System. setOut (ps); // set to use the new output stream int age = 18; System. out. println ("age variable defined successfully, initial value: 18"); String sex = "female"; System. out. println ("gender variable defined successfully, initial value: female"); String info = "this is "+ Sex +" children, should have "+ age +" years old "; System. out. println ("integrate two variables as info string variables and the result is" + info); System. setOut (out); // restore the original output stream System. out. println ("the program is running successfully. Check the log file. ");} Catch (FileNotFoundException e) {e. printStackTrace ();}}}
The log is as follows:
The age variable is defined successfully. The initial value is 18.
The gender variable is defined successfully. The initial value is female.
Integrate the two variables into the info string variable. The result is that this variable is a girl and should be 18 years old.
Summary:
This method saves the out member variable of the System class as a temporary variable, creates a new file output stream, and sets the output stream as the new output stream of the System class. And output continuous debugging information 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.