Java IO之處理流(緩衝流、轉換流)

來源:互聯網
上載者:User

標籤:緩衝流   處理流   轉換流   

一、處理流:

增強功能,提供效能,在節點流之上。

二、節點流與處理流的關係

節點流(位元組流、字元流)處於IO操作的第一線,所有操作必須通過它們進行;
處理流可以對其他流進行處理(提高效率或操作靈活性)。

三、緩衝流 1、位元組緩衝流
BufferedInputStreamBufferedOutputStream
package IOBuffer;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * 處理流(位元組緩衝流) * 位元組流檔案拷貝+緩衝流,提高效能 * 緩衝流(節點流) */@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) throws IOException     {        //1、建立聯絡  源存在(且為檔案)+目的地(檔案可以不存在)                        File src = new File(srcPath);        File dest = new File(destPath);        if(!src.isFile())        {            System.out.println("只能拷貝檔案");            throw new IOException("只能拷貝檔案");        }        //2、選擇流 緩衝流(位元組輸入資料流)              InputStream is = new BufferedInputStream(new FileInputStream(src));        OutputStream os =new BufferedOutputStream(new FileOutputStream(dest)) ;        //3、檔案拷貝  迴圈+讀取+寫出        byte[] flush = new byte[1024];        int len = 0;            while(-1!=(len = is.read(flush)))        {            //寫出            os.write(flush,0,len);        }        os.flush();//強制刷出                   //關閉流 先開啟後關閉        os.close();        is.close();    }}
2、字元緩衝流
BufferedReader  新增readLine()讀取一個文本行。 BufferedWriter  新增newLine()寫入一個行分隔字元。
package IOBuffer;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;/** *  * 字元緩衝流+新增方法(不能發生多態) */public class Demo02 {    public static void main(String[] args) {        String srcPath = "G:/oo.txt";        String destPath = "G:/xx.txt";              //建立源        File src = new File(srcPath);        File dest = new File(destPath);        //選擇流   緩衝流   如果後面要使用新增方法,就不能使用多態了。        //如果沒有使用子類的新增方法,可以使用多態方式。        /*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 =new BufferedReader(new FileReader(src)) ;            writer = new BufferedWriter(new FileWriter(dest));            //讀取操作            //新增方法操作的字元緩衝流            String line = null;//一行一行讀取 BufferedReader新增readLine()            while(null!=(line = reader.readLine()))            {                writer.write(line);                //writer.append("\r\n");//分行符號                writer.newLine();//分行符號  新增方法            }            writer.flush();        } catch (FileNotFoundException e) {            e.printStackTrace();            System.out.println("檔案不存在");        } catch (IOException e) {            e.printStackTrace();        }        finally        {            if(null!=reader)            {                try {                    writer.close();                    reader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }           }}
四、轉換流

(一)位元組流轉換為字元流,處理亂碼(編碼集、解碼集)
解碼:二進位–>解碼字元集–>字元
編碼:字元–>編碼字元集–>二進位

(二)為什麼會出現亂碼?
1、解碼與編碼的字元集不統一
2、位元組缺少,長度丟失

(三)檔案亂碼(通過轉換流進行處理)

package IOConver;import java.io.UnsupportedEncodingException;public class Demo01 {    public static void main(String[] args) {        test01();        System.out.println("-----------");        test02();    }    //解碼與編碼字元集字元集必須相同    public static  void test01()    {        //解碼byte-->char        String str = "中國";//UTF-8        //編碼 char-->byte        byte[] data = str.getBytes();        //編碼與解碼的字元集統一        System.out.println(new String(data));        try {            data  = str.getBytes("gbk");//設定編碼字元集    編碼            //不統一字元集,出現亂碼            System.out.println(new String(data));//解碼        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        byte[] data2;        try {            //編碼            data2 = "中國".getBytes("GBK");            //解碼            str = new String(data2,"GBK");            //str = new String(data2);//不指定 預設解碼UTF-8 會出現亂碼            System.out.println(new String(str));        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }                   }    //位元組缺少,長度丟失    public static  void test02(){        String str = "中國";        byte[] data;        data = str.getBytes();//編碼        //位元組數不完整        System.out.println(new String(data,0,4));    }}

運行結果:

?й?中國-----------中?
package IOConver;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;/** * 轉換流:位元組轉為字元 * 1、輸出資料流OutputStreamWriter  編碼 * 2、輸入資料流InputStreamReader  解碼 */public class Demo02 {    public static void main(String[] args) throws IOException {        //輸入檔案  解碼 (位元組到字元)   讀取  要顯示          //指定解碼字元集    BufferedReader字元流--InputStreamReader轉換流--FileInputStream位元組流        BufferedReader br = new BufferedReader                (                    new InputStreamReader                    (                        new FileInputStream(new File("g:/writer.txt")),"UTF-8"                    )                );//指定字元解碼集        //寫出檔案     編碼(字元到位元組)        BufferedWriter bw = new BufferedWriter                (                    new OutputStreamWriter                    (                        new FileOutputStream(new File("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();    }}

運行結果:

每個人都有青春,每個青春都有一個故事,每個故事都有一個遺憾,每個遺憾卻都存在著他的美好。ouye
五、常用流關係圖

Java IO之處理流(緩衝流、轉換流)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.