The read and write methods of the file byte input and output stream use byte arrays to read and write data, that is, to process data in bytes. Therefore, byte streams do not operate well with Unicode characters. For example, a Chinese character occupies 2 bytes in the file. If a byte stream is used, "garbled characters" will appear if read improperly.
Corresponding to the FileInputStream and FileOutputStream byte streams are the FileReader and FileWriter character streams (file character input and output streams). FileReader and FileWriter are subclasses of Reader and Writer respectively, and their construction methods are:
FileReader(Stringfilename);FileReader(Filefilename);Fi1eWriter(Stringfilename);FileWriter(Filefilename);FileWriter(Stringfilename,booleanappend);FileWriter(Filefilename,booleanappend);
The read and write methods of character input streams and output streams use character arrays to read and write data, that is, to process data with characters as the basic unit.
For example:
importjava.io.*;publicclassMain{publicstaticvoidmain(Stringargs[]){FilesourceFile=newFile(a.txt);//The file read FiletargetFile=newFile(b.txt);//The file written charc[]=newchar [19];//char array try{Writerout=newFileWriter(targetFile,true);//output stream pointing to the destination Readerin=newFileReader(sourceFile);//input stream pointing to the source intn=-1;while(( n=in.read(c))!=-1){out.write(c,0,n);}out.flush();out.close();}catch(IOExceptione){System.out.println (Error+e);}}}
Note : For Writer streams, the write method first writes data to the buffer. Whenever the buffer overflows, the contents of the buffer are automatically written to the destination. If the stream is closed, the contents of the buffer will be written immediately to destination. The stream calls the flush() method to immediately flush the current buffer, that is, to write the contents of the current buffer to the destination.