1. Requirements: Copy the A.txt content under the current project directory to the B.txt in the current project directory.
Data Source:
A.txt--reading data--character conversion stream--InputStreamReader
Destination:
B.txt--Write data--character conversion stream--OutputStreamWriter
inputstreamreader/OutputStreamWriter is not only the conversion stream (converting the byte stream to a character stream), but also the specific implementation subclass of the character stream Reader/writer .
2. code example:
1 Packagecn.itcast_04;2 3 ImportJava.io.FileInputStream;4 ImportJava.io.FileOutputStream;5 Importjava.io.IOException;6 ImportJava.io.InputStreamReader;7 ImportJava.io.OutputStreamWriter;8 9 /*Ten * Requirement: Copy a.txt content from current project directory to b.txt in current project directory One * A * Data Source: - * a.txt--read data--character conversion stream--InputStreamReader - * Destination: the * B.txt--Write data--character conversion stream--OutputStreamWriter - */ - Public classCopyfiledemo { - Public Static voidMain (string[] args)throwsIOException { + //Encapsulating Data Sources -InputStreamReader ISR =NewInputStreamReader (NewFileInputStream ( +"A.txt")); A //Package Destination atOutputStreamWriter OSW =NewOutputStreamWriter (NewFileOutputStream ( -"B.txt")); - - //Read and write Data - //Mode 1 - //int ch = 0; in //While ((ch = isr.read ())! =-1) { - //osw.write (CH); to // } + - //Mode 2 the Char[] CHS =New Char[1024]; * intLen = 0; $ while(len = Isr.read (CHS))! =-1) {Panax NotoginsengOsw.write (CHS, 0, Len); - //Osw.flush (); the } + A //Freeing Resources the osw.close (); + isr.close (); - } $}
Java Fundamentals Hardening IO Flow Note 35:inputstreamreader/outputstreamwriter Copy text file case 01