1. 程式人生 > >Java學習筆記之--------IO流之緩衝流

Java學習筆記之--------IO流之緩衝流

緩衝流

位元組緩衝流:BufferedInputStream,BufferedOutputStream

字元緩衝流:BufferedReader,readLine(),BufferedWriter,newLine()

我們實現位元組流檔案拷貝+緩衝流,提高效能:

public class BufferedByteDemo {
    public static void main(String[] args) throws IOException {
        copyFile("D:/xp/test/Demo03.java","D:/xp/test/char.txt");
    }
    public static void copyFile(String srcPath, String destPath) throws IOException {
        //1.建立聯絡  源(存在且為檔案)+ 目的地(檔案可以不存在)
        File src = new File(srcPath);
        File dest = new File(destPath);
        //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();
    }
}

用緩衝流實現字元緩衝流+新增方法(不能發生多型):

public class BufferedCharDemo {
    public static void main(String[] args) {
        //建立源
        File src = new File("D:/xp/test/Demo03.java");
        File dest = new File("D:/xp/test/char.txt");
        //選擇流
        BufferedReader reader = null;
        BufferedWriter wr = null;
        try {
            reader = new BufferedReader(new FileReader(src));
            wr = new BufferedWriter(new FileWriter(dest));
            //讀取操作
            /*char[] flush = new char[10];
            int len = 0;
            while (-1 != (len=reader.read(flush))){
                wr.write(flush,0,len);
            }*/
            //新方法
            String line = null;
            while (null != (line = reader.readLine())){
                wr.write(line );
                wr.newLine();//換行符號
            }
            //強制刷出
            wr.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("原始檔不存在!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("檔案讀取失敗!");
        } finally {
            try {
                if (null != wr){
                    wr.close();
                }
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

以上就是緩衝流的應用例項。