Java 输入与输出(I\O)之字节缓冲流【BufferedInputStream】【BufferedOutputStream】详解

缓冲流是Java I/O中的一个重要概念,它可以提高文件读写的性能。

由于磁盘的IO处理速度远低于内存的读写速度。

为了提高文件读写性能,我们可以使用缓冲流。缓冲流使用内存缓冲区,可以一次性读取或写入大量数据,从而减少与磁盘的交互次数,提高整体性能。

缓冲流有两种类型:缓冲字节流和缓冲字符流。

缓冲字节流包括BufferedInputStream和BufferedOutputStream,而缓冲字符流包括BufferedReader和BufferedWriter。

缓冲流是装饰流(处理流),不能直接访问数据源,必须使用节点流作为参数,通过节点流的桥梁实现访问数据源的目的。

字节缓冲流

字节缓冲流包括BufferedInputStream和BufferedOutputStream,它们分别继承自InputStream和OutputStream。它们是装饰流,可以用来装饰节点流和处理流,以增加缓冲功能,提升处理效率。

字节缓冲流的常用方法:

下面是一个字节缓冲流的演示例程:

cpp 复制代码
package IOStream;
import java.io.*;
public class BufferedStreamDemo {
	public static void copyFileWithBuffered(String srcPath,String destPath) {
        File src = new File(srcPath);
        File dest = new File(destPath);
        byte[] buffer = new byte[1024];
        int len;
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest))){
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
            }
		} catch (IOException e) {
			e.printStackTrace();
		}    
	}
	
	public static void main(String[] args) {
        String sPath = "D:/src/mp4/九寨沟风景.mp4";
        String dPath = "D:/src/mp4/九寨沟风景B.mp4";
        copyFileWithBuffered(sPath, dPath);
        System.out.println("文件复制成功!");
	}
}

测试结果:

参考文献与博客:
Java中的缓冲流详细解析
Java学习之缓冲流的原理详解
java 缓冲流的概念使用方法以及实例详解

相关推荐
RainbowSea16 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea16 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑20 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613520 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊21 小时前
Java学习第22天 - 云原生与容器化
java
渣哥1 天前
原来 Java 里线程安全集合有这么多种
java
间彧1 天前
Spring Boot集成Spring Security完整指南
java
间彧1 天前
Spring Secutiy基本原理及工作流程
java
Java水解1 天前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆1 天前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试