一、三个 Static variables
Java.lang.System provides three static variables
- System.in (default keyboard)
- System.out (Default monitor)
- System.err
Second, rewrite to the method
The system provides three redirection methods
Method |
Description |
static void Seterr (PrintStream errr) |
REDIRECT standard error output stream |
static void SetIn (InputStream in) |
REDIRECT Standard input stream |
static void SetOut (PrintStream out) |
REDIRECT Arrivals output stream |
Iii. Example 3.1, redirect input stream
PackageCom.pb.io.reio;ImportJava.io.BufferedReader;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.InputStreamReader;Importjava.io.UnsupportedEncodingException;/** REDIRECT Input * 1. There is an already initialized InputStream input stream * 2. Call the System.setin () method to redirect the standard input stream to the destination input stream * 3. Read the contents of the system.in*/ Public classReIn { Public Static voidMain (string[] args)throwsunsupportedencodingexception {Try { //1. Declaring an input streamFileInputStream fis=NewFileInputStream ("D:/test/s1.txt"); //2. redirectionsystem.setin (FIS); //3. Read the contents of the system.in standard input streamBufferedReader br=NewBufferedReader (NewInputStreamReader (system.in, "gb2312"));//Set character encoding//4. Output the contents of the system.inString line=NULL; while((Line=br.readline ())! =NULL) {System.out.println (line); } //5. Close the streamBr.close (); Fis.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } }}
3.2. REDIRECT Output stream
PackageCom.pb.io.reio;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.PrintStream;/** redirect the output stream * 1. Initialize the PrintStream object * 2. Call the System.setout () method to redirect the subscript output stream to the PrintStream object * 3. Operation System.out Flow,*/ Public classReout { Public Static voidMain (string[] args) {Try { //1. Declaring an output stream PrintStream objectPrintStream ps=NewPrintStream (NewFileOutputStream ("D:/test/ps.txt",true));//Append Content//2. Redirect the output streamSystem.setout (PS); //3. Using the PrintStream object to write information to the streamSYSTEM.OUT.PRINTLN ("The test redirect succeeded No!") "); System.out.println (Newreout ()); Ps.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } }}
Java starts from scratch 38 (Java io-redirect IO)