IO operations for Java: The system class supports IO.

Source: Internet
Author: User

Goal:

1, master the three kinds of system support for IO:

System.out

System.in

System.err

2, master the difference between System.out and System.err.

3, master input, output redirect.

Constants of the System class

Java has some support for the system class for IO, and three constants are prefabricated.

PrintStream Out,printstream Err,inputstream in.

Variables declared with static final are global constants, and all word letters must be capitalized if they are constants. But not here, is a legacy of Java history.

System.out

Using the System.out output is to define the output location in the display.

The Filloutputstream output location is defined in the file, while the System.out is positioned on the screen.

Use OutputStream to complete the on-screen output.

PrintStream is the OutputStream subclass.

 Packageclass set;ImportJava.io.OutputStream;Importjava.io.IOException; Public classsystemdemo01{ Public Static voidMain (String args[]) { OutputStream out=System.out;//the output stream at this point is output to the screen        Try{ out.write ( "Hello World!!!".    GetBytes ()); Output to the screen}Catch(IOException e) {e.printstacktrace (); //Printing Exceptions        }        Try{ out.close (); //Close output stream}Catch(IOException e) {e.printstacktrace (); }    }};

Output Result:

Interpretation:

OutputStream is normally outputstream out=new OutputStream (f F), where f specifies the file output path, but this gives the out assignment System.out instance directly, because this

The output object of the instance is the screen, so the output path of the out is the screen.

Obviously, this is the embodiment of the object polymorphism, depending on the implementation of the subclass. The completed functions are also different .

Note: The Receive object for the OutputStream write method is an array of byte[]. Use GetBytes () to convert to a byte array. and close the output stream.

System.err

The standard output of the error. If there is an error in the program, use System.err to print the output directly.

 Package class set;  Public class systemdemo01{    publicstaticvoid  main (String args[]) {            = " Hello ";        // declaring a string            that is not a number Try {                System.out.println (Integer.parseint (str));     // Transformation            } Catch (Exception e) {                System.err.println (e);     }};

Output Result:

Java.lang.NumberFormatException:For input string: "Hello"

If you do not have system.err at this time, with System.out is not the same?

Err and out differ.

Both can print error message, but generally speaking,System.out is to display information to the user , and System.err is not want the user to see , backstage display. specifically displays the error.

To output errors, it is best not to use System.out and system.err directly.

System.in

is actually a keyboard input stream , which itself is a InputStream type object, you can use this object to read data information from disk .

InputStream is an input stream, the input stream can definitely be read from the specified location, before the Fillinputstream, is read from the file,

 Packageclass set;ImportJava.io.InputStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{ inputstream input = system.in; receiving data from the keyboard        byte b[] = new BYTE[5]; Open up space to receive dataSystem.out.print ("Please enter content:");//Prompt Information        int Len=Input.read (b); Receive DataSYSTEM.OUT.PRINTLN ("Input content:" +New String (b,0 , Len))        ;    Input.close (); //close the input stream    }};

Operation Result:

Interpretation: First define a InputStream object input, assigned to system.in, so that it can receive the object from the keyboard, and then open a byte array, to receive the input data,

Input.read (array), assigns the input data to a byte array, eventually returns the input array size len, and uses the new String () method to convert a byte array to a String type output.

notethat the new String (B,o,len), must specify the output header and tail, if not specified, it is possible to place no data where the output, such as I defined a 36-space array, after input, the output is as follows:

But data input, the above operation is there a problem?

Issue 1: The length of the array is specified, and if the data entered now exceeds the length range, only part of the data can be entered.

Problem 2:byte Array length is odd , there may be a problem with Chinese characters garbled . Because a Chinese character occupies two bytes.

So, if you do not know the length of the byte array, can you complete the input requirements?

It can only be done by judging the flag bit.

 Packageclass set;ImportJava.io.InputStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{ inputstream input = system.in;    //receiving data from the keyboard        StringBuffer buf = new StringBuffer (); Using StringBuffer to receive dataSystem.out.print ("Please enter content:");//Prompt Information        int temp = 0; Receive Content         while((Temp=input.read ())!=-1){            char c = (char) temp; Turning data into characters            if (c== ' \ n '){//exit the loop, enter a enter to indicate the input is complete                  Break ;    }  Buf.append (c)  ; //Save content} System.out.println ("The input content is:" + buf);    Input.close (); //close the input stream    }}; 

Ideas:

Defines a StringBuffer class that is used to receive a save string, for each input character, through the Input.read () method, reads a byte, assigns a value to temp, when read to the ENTER key, the value of temp is-1,

Then temp is converted to char type, and after char type, it can be stitched to the StringBuffer object.

Note: because the carriage return is also a character, so if the obtained character is a carriage return, then exit the loop, if (c== ' \ n ') break;

However, the above code, input Chinese words will be an error .

To achieve these functions, you can only pass the Bufferreader class in the next section.

Input and output redirection

The System class allows you to change the source of the system.in input stream, as well as the output position of the System.out and system.err two output streams.

SetOut instances:

 Packageclass set;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.PrintStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{ system.setout(New printstream(New FileOutputStream("D:" + File.separator + "Red.txt"));//System.out Output REDIRECT System.out.print("www.mldnjava.cn");//Output , no longer output to the screen           System.out.println(", Li Xinghua") ; }};  

At this point the output is not in the console, but in the specified file.

The error redirection can actually be done through this operation. System.out is the information that you want users to see, and if there are errors, it's best to save them.
 Packageclass set;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.PrintStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{String str= "Hello";//declaring a string that is not a number        Try{System.out.println (Integer.parseint (str)); //Transformation}Catch(Exception e) {Try {system.setout(                NewPrintStream (NewFileOutputStream ("D:" + File.separator + "Err.log"));//Output redirection}Catch(Exception E1) {} System.out.println (e); }    }};

Note the position of the System.setout method, placed in the middle of the try catch, so that the output redirection is changed when an error occurs .

REDIRECT for System.err.

Use System.err to output information to the screen. In this case, use the memory operation flow for the sake of convenience.

 Packageclass set;ImportJava.io.ByteArrayOutputStream;ImportJava.io.PrintStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{  bytearrayoutputstream Bos=NULL;// declaring memory output stream Bos         =New Bytearrayoutputstream() ;//instantiation of        System.    Seterr (New PrintStream(BOS)); Output redirection System.Err. Print ("www.mldnjava.cn");//error output, no longer output to the screenSystem.Err. println ("Li Xinghua");//output to in-memorySystem.out.println (Bos) ;//output in-memory data    }};

Output Result:

Idea: Redirect Error output location is memory, so, when printing error, will be redirected to the memory object instance input memory, output, output corresponding memory object instance inside the data.

Recommendation: It is generally not recommended to modify the output location of System.err. Because this information does not want the user to see.

system.in redirection

By default, system.in is pointing to the screen, or you can change the position of the input by using the Setin method, for example, now read from a file.

 Packageclass set;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.InputStream; Public classsystemdemo01{ Public Static voidMain (String args[])throwsexception{ system.setin(New FileInputStream("D:" + File.separator + "Red.txt"));//Setting the input redirection           InputStream input = system.in;//receive data from a file            byteB[] =New byte[1024];//open up space to receive data            intLen =Input.read (b); ReceiveSYSTEM.OUT.PRINTLN ("Input content:" +New String (b,0 , Len))            ;    Input.close (); //close the input stream        }    };

This allows you to read the data directly from the target file, assign it to a byte array, and then output the array without the keyboard input.

IO operations for Java: The system class supports IO.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.