缓冲流简介

缓冲流简介

缓冲流里面通过了一个缓冲区 用来提高文件读写的速度

字符缓冲流

BufferedReader
BufferedWriter

字节缓冲流

BufferedInputStream
BufferedOutputStream
刷新缓冲区 你不刷新也没有关系 在关闭流的时候会帮你自动刷新

字符缓冲流
//输入文件操作对象
File read = new File("1.png");
//输出文件操作对象
File write = new File("2.png");
try {
    Reader reader = new FileReader(read);
    Writer writer = new FileWriter(path);
    BufferedReader bufferedReader = new BufferedReader(reader);
    BufferedWriter bufferedWriter = new BufferedWriter(writer);
    int date = 0;
    char[] ch = new char[10];
    while((date = bufferedReader.read(ch)) != -1){
        bufferedWriter.write(ch,0,date);
        System.out.println(new String(ch,0,date));
    }
    bufferedReader.close();
    bufferedWriter.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch (IOException e) {
    e.printStackTrace();
        }
字节缓冲流
//输入文件操作对象
File read = new File("1.png");
//输出文件操作对象
File write = new File("2.png");
//输入文件流
InputStream inputStream = null;
//输出文件流
OutputStream outputStream = null;
try {
    inputStream = new FileInputStream(read);
    outputStream = new FileOutputStream(write);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
try {
    byte[] bytes = new byte[514];
    int date = 0;
    //输入文件缓冲流
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    //输出文件缓冲流
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
    //将inputStream的数据转换成byte数组
    while ((date = bufferedInputStream.read(bytes)) != -1) {
        //将byte数组导入到outputStream中
        bufferedOutputStream.write(bytes,0,date);
    }
    //关闭对象
    //可以只关闭外部流,关闭外部流时缓冲流自动刷新
    bufferedInputStream.close();
    bufferedOutputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}