Character output stream: Writer class: Subclasses that need it when used
Limitations: Only text files can be written, other files cannot be written
Method:
Packagedemo;ImportJava.io.FileWriter;Importjava.io.IOException; Public classWriterdemo { Public Static voidMain (string[] args)throwsIOException {FileWriter fw=NewFileWriter ("D:\\java.txt"); Fw.write (100);//Write: DFw.flush (); //Note that each write is to use the Flush method Char[] cs = {' A ', ' B ', ' C ', ' d ', ' e ' }; Fw.write (CS);//write: ABCDEFw.flush (); Fw.write (CS,1, 2);//write: BCFw.flush (); Fw.write ("Java");//write: JavaFw.flush (); Fw.close (); }}
Character input stream read text: Reader class
There are also limitations, only text files can be read
Method (use Java.txt text written on top):
There are two different ways:
Packagedemo;ImportJava.io.FileReader;Importjava.io.IOException; Public classReaderdemo { Public Static voidMain (string[] args)throwsIOException {FileReader fr=NewFileReader ("D:\\java.txt"); intLen = 0; while(len = Fr.read ())! =-1) {System.out.print (Char) len); } fr.close (); System.out.println ("Two Methods dividing line"); FileReader FR1=NewFileReader ("D:\\java.txt"); Char[] ch =New Char[1024]; while(len = fr1.read (ch))! =-1) {System.out.print (NewString (CH, 0, Len)); } fr1.close (); }}
To copy a text file:
Packagedemo;ImportJava.io.FileReader;ImportJava.io.FileWriter;Importjava.io.IOException;/** Character stream copy text file, and must be a text file * Character stream query native default encoding table, Simplified Chinese GBK * FileReader read Data source * FileWriter write to Data purpose*/ Public classCopy { Public Static voidMain (string[] args) {FileReader fr=NULL; FileWriter FW=NULL; Try{FR=NewFileReader ("C:\\1.txt"); FW=NewFileWriter ("D:\\1.txt"); Char[] Cbuf =New Char[1024]; intLen = 0; while(len = Fr.read (cbuf))! =-1) {fw.write (Cbuf,0, Len); Fw.flush (); } } Catch(IOException ex) {System.out.println (ex); Throw NewRuntimeException ("Replication Failed"); } finally { Try { if(FW! =NULL) Fw.close (); } Catch(IOException ex) {Throw NewRuntimeException ("Release resource Failed"); } finally { Try { if(FR! =NULL) Fr.close (); } Catch(IOException ex) {Throw NewRuntimeException ("Release resource Failed"); } } } }}
Java Learning Note 38 (character stream)