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();
            }
        }
    }
}

以上就是缓冲流的应用实例。

猜你喜欢

转载自blog.csdn.net/wangruoao/article/details/83993555