I. Overview of IO streams
The 1.IO stream is used to transfer data between devices.
The operation of the data in 2.Java is carried out in a stream manner.
3. Classification:
1) data by operation: Byte Stream (There are early, can transmit any data) and character stream (ASCII code table, Unicode code table < two bytes >).
2) Press flow: input stream and output stream.
4. Abstract base class
1) byte stream: Inputstream,outputstream
2) Character stream: Reader,writer
two. Io Stream instance
1.FileWriter class Instances
1 //Create a new Filewriterdemo class2 ImportJava.io.*;3 4 Public classFilewriterdemo {5 6 Public Static voidMain (String []args)throwsioexception{7 //Create a new FileWriter class and create a new file Text.txt8FileWriter fw=NewFileWriter ("Test.txt");9 //writes data to memory, written in memory onlyTenFw.write ("ABCDE"); One //refreshes the data and writes the data to the file A Fw.flush (); - //can be written infinitely -Fw.write ("haha"); the - Fw.flush (); - //Refresh on shutdown - fw.close (); + } -}
Run results
2.IO exception
1 //Create a new Filewriterdemo class2 ImportJava.io.*;3 4 Public classFilewriterdemo {5 6 Public Static voidMain (String []args) {7 //defining classes outside of a try8FileWriter fw=NULL;9 Ten Try{ One //Initialize Afw=NewFileWriter ("Test.txt"); - -Fw.write ("ABCDE"); the } - - Catch(IOException e) { - + System.out.println (e.tostring ()); - } + //try to put the closed data stream into the finally when handling the exception A finally{ at - Try { - //If there is more than one, use multiple judgements and not in a single, such as: - //if (fw! ==null&&fw== ""), etc. - if(fw!=NULL) - in fw.close (); - to}Catch(IOException e) { + - System.out.println (e.tostring ()); the } * } $ }Panax Notoginseng}
3 Fileread class Instances
3.1 One character read at a time
1 ImportJava.io.*;2 Public classFileRead {3 4 Public Static voidMain (string[] args)throwsioexception{5 //Create a new FileReader class6FileReader fd=NewFileReader ("Test.txt");7 //when the data is read from a file, an int is returned at the end of the data-one that ends8 intCh=0;9 while((Ch=fd.read ())!=-1){TenSystem.out.println ("ch=" + (Char) ch); One } A /* - While (true) { - int Ch=fd.read (); the //When ch=-1, roll -out cycle - if (ch==-1) - Break ; - //output read data and force conversion to char type + System.out.println ("ch=" + (char) ch); - } + */ A //Turn off Data flow at fd.close (); - - } - -}
3.2 reading from the array
1 ImportJava.io.*;2 3 Public classFilereadstr {4 5 Public Static voidMain (string[] args)throwsioexception{6 7FileReader fd=NewFileReader ("Test.txt");8 //when reading data in an array, the array is typically defined as 1024 times times the number9 Char[]buf=New Char[1024]; Ten intNum=0; One while((Num=fd.read (BUF))!=-1){ A //from the first start of the array to the end of the last -System.out.println (NewString (buf,0, num)); - } the - fd.close (); - } - +}
Run results
Java IO (Input output) flow < one >