Java IO processing stream (buffered stream, transform stream)

Source: Internet
Author: User
Tags file copy

one, processing flow:

Enhanced functionality that provides performance on top of node streams.

the relationship between node flow and processing flow

The node stream (byte stream, character stream) is in the front line of IO operation, and all operations must be done through them;
processing streams can handle other flows (increasing efficiency or operational flexibility).

third, buffer flow 1, byte buffer stream
BufferedInputStreamBufferedOutputStream
 PackageIobuffer;ImportJava.io.BufferedInputStream;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;/** * Processing stream (Bytes buffered stream) * Byte stream file copy + buffered stream, improved performance * buffered stream (node stream) */@SuppressWarnings("All") Public  class Demo01 {     Public Static void Main(string[] args) {String Srcpath ="G:/1314.jpg"; String DestPath ="G:/try/520.jpg";Try{copyFile (Srcpath,destpath); }Catch(IOException e)        {E.printstacktrace (); }    } Public Static void CopyFile(String srcpath,string DestPath)throwsIOException {//1, establish contact source exists (and file) + destination (file can not exist)File src =NewFile (Srcpath); File dest =NewFile (DestPath);if(!src.isfile ()) {System.out.println ("Copy files only");Throw NewIOException ("Copy files only"); }///2, select Stream buffer stream (byte input stream)InputStream is =NewBufferedinputstream (NewFileInputStream (SRC)); OutputStream OS =NewBufferedoutputstream (NewFileOutputStream (dest));//3, File copy loop + Read + write        byte[] Flush =New byte[1024x768];intLen =0; while(-1! = (len = is.read (flush))) {//write outOs.write (Flush,0, Len); } os.flush ();//Forced Brush out        //Close flow first open and then offOs.close ();    Is.close (); }}
2. Character Buffer stream
BufferedReader  新增readLine()读取一个文本行。 BufferedWriter  新增newLine()写入一个行分隔符。
 PackageIobuffer;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.IOException;/** * * Character Buffer stream + new method (cannot occur polymorphic) */ Public  class Demo02 {     Public Static void Main(string[] args) {String Srcpath ="G:/oo.txt"; String DestPath ="G:/xx.txt";//Create sourceFile src =NewFile (Srcpath); File dest =NewFile (DestPath);//Select stream buffer stream if you want to use the new method later, you cannot use polymorphism.         //If there are no new methods for using subclasses, you can use polymorphic mode.         /*reader Reader = null;        writer writer = null;        Reader =new BufferedReader (new FileReader (SRC));        writer = new BufferedWriter (new FileWriter (dest)); Reader.read (flush) writer.write (flush,0,len) * /BufferedReader reader =NULL; BufferedWriter writer =NULL;Try{reader =NewBufferedReader (NewFileReader (SRC)); writer =NewBufferedWriter (NewFileWriter (dest));//Read operation            //New method operation character Buffer streamString line =NULL;//One line read BufferedReader new ReadLine ()             while(NULL! = (line = Reader.readline ())) {Writer.write (line);//writer.append ("\ r \ n");//Line breakWriter.newline ();//New line break method} writer.flush (); }Catch(FileNotFoundException e)            {E.printstacktrace (); System.out.println ("file does not exist"); }Catch(IOException e)        {E.printstacktrace (); }finally{if(NULL!=reader) {Try{Writer.close ();                Reader.close (); }Catch(IOException e)                {E.printstacktrace (); }            }        }           }}
Iv. Conversion Flow

(a) byte stream conversion to character stream, processing garbled (encoding set, decoding set)
Decoding: Binary –> decoding character set –> character
Encoding: Character –> coded character set –> binary

(b) Why are garbled characters appearing?
1, decoding and encoding of the character set is not uniform
2, byte missing, missing length

(iii) garbled file (processed by conversion stream)

Package Ioconver;import java.io.UnsupportedEncodingException; Public classDemo01 { Public Static void Main(string[] args)        {test01 (); System. out. println ("-----------");    Test02 (); }//decoding must be the same as coded character set character set     Public Static  void test01()    {//Decode Byte-->charString str ="China";//utf-8        //code Char-->byte        byte[] data = Str.getbytes ();//encoding and decoding of the character set UnitySystem. out. println (NewString (data));Try{data = Str.getbytes ("GBK");//Set coded character set encoding            //non-uniform character set, garbledSystem. out. println (NewString (data));//decoding}Catch(Unsupportedencodingexception e)        {E.printstacktrace (); }byte[] data2;Try{//CodingData2 ="China". GetBytes ("GBK");//decodingstr =NewString (Data2,"GBK");//str = new String (data2);//Do not specify default decoding UTF-8 will appear garbledSystem. out. println (NewString (str)); }Catch(Unsupportedencodingexception e)        {E.printstacktrace (); }                   }//bytes missing, missing length     Public Static  void test02() {String str ="China";byte[] data; data = Str.getbytes ();//Coding        ///Byte count is incompleteSystem. out. println (NewString (data,0,4)); }}

Operation Result:

?й?中国-----------中?
 PackageIoconver;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;/** * Convert stream: Byte to character * 1, output stream outputstreamwriter encode * 2, input stream InputStreamReader decode */ Public  class Demo02 {     Public Static void Main(string[] args)throwsIOException {//Input file decoding (bytes to characters) read to display        //Specify decoding character set BufferedReader character stream--inputstreamreader convert stream--fileinputstream byte flowBufferedReader br =NewBufferedReader (NewInputStreamReader (NewFileInputStream (NewFile ("G:/writer.txt")),"UTF-8")                );//Specify character decoding set        //write file encoding (characters to bytes)BufferedWriter BW =NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream (NewFile ("G:/try/abdec.txt")),"UTF-8")                ); String info =NULL; while(NULL! = (info = br.readline ())) {System.out.println (info); Bw.write (info+"\ r \ n");        } bw.flush ();        Bw.close ();    Br.close (); }}

Operation Result:

每个人都有青春,每个青春都有一个故事,每个故事都有一个遗憾,每个遗憾却都存在着他的美好。ouye
v. Common Flow diagram

Java IO processing stream (buffered stream, transform stream)

Related Article

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.