【从零开始学Java | 第三十七篇】缓冲流(Buffered Stream)

张开发
2026/4/17 13:11:49 15 分钟阅读

分享文章

【从零开始学Java | 第三十七篇】缓冲流(Buffered Stream)
目录前言一、字节缓冲流1.单个字节拷贝2.多个字节拷贝二、字符缓冲流1.readLine()读取一行2.newLine()跨平台换行总结前言在前面的博客中我们学习了 Java I/O 流的基础字节流和字符流。如果你在实际开发中直接使用基础的FileInputStream去读取一个几百 MB 的视频文件你会发现程序卡得像蜗牛一样。为什么会这么慢因为基础流默认是直接与硬盘打交道的而硬盘的读写速度远远跟不上内存和 CPU 的速度。为了解决这个 I/O 性能瓶颈Java 提供了——缓冲流Buffered Stream。一、字节缓冲流原理底层自带了长度为8192的缓冲区提高性能。缓冲流是一个高级流是对基础流做了包装 因此在构造缓存流时构造方法的参数要是基础流。方法名说明publicBufferedInputStream(InputStream is)把基础流包装成高级流提高读取的效率publicBufferedOnputStream(OnputStream is)把基础流包装成高级流提高写出的效率1.单个字节拷贝public class Test { public static void main(String[] args) throws IOException { BufferedInputStream bis new BufferedInputStream(new FileInputStream(src\\a.txt)); BufferedOutputStream bos new BufferedOutputStream(new FileOutputStream(src\\a_copy.txt)); int b; while((b bis.read()) ! -1){ bos.write(b); } bos.close(); bis.close(); } }2.多个字节拷贝public class Tets { public static void main(String[] args) throws IOException { BufferedInputStream bis new BufferedInputStream(new FileInputStream(src\\a.txt)); BufferedOutputStream bos new BufferedOutputStream(new FileOutputStream(src\\a1_copy.txt)); byte[] bytes new byte[1024]; int len; while((len bis.read(bytes)) ! -1){ bos.write(bytes, 0, len); } bos.close(); bis.close(); } }二、字符缓冲流原理底层自带了长度为8192的缓冲区提高性能。由于字符流本身带有缓冲流所以基础字符流使用高级缓冲流提高的效率不太明显但是其中有两个常用的方法。方法名说明public BufferedReader(Reader r)基本流包装成高级流public BufferedWriter(Writer r)基本流包装成高级流字符缓冲流特有方法字符缓冲输入流特有方法说明public StringreadLine()读一行数据如果没有数据可读返回null字符缓冲输出流特有方法说明public StringnewLine()跨平台的换行mac\rWindows\r\nLinux\n1.readLine()读取一行读取单行public class Test { public static void main(String[] args) throws IOException { BufferedReader br new BufferedReader(new FileReader(src\\a.txt)); String line br.readLine(); System.out.println(line); br.close(); } }读取整个文件以null为结束条件public class Test { public static void main(String[] args) throws IOException { BufferedReader br new BufferedReader(new FileReader(src\\a.txt)); String line; while((line br.readLine()) ! null){ System.out.println(line); } // System.out.println(line); br.close(); } }2.newLine()跨平台换行不同平台下的换行符不同mac\rWindows\r\nLinux\n使用该方法可以将这些换行符进行统一。public class Test02 { public static void main(String[] args) throws IOException { BufferedWriter bw new BufferedWriter(new FileWriter(b.txt)); bw.write(Unicode (UTF-8)万国码目前互联网最通用的标准。); bw.newLine(); bw.write(在 UTF-8 编码下英文占 1 个字节中文占 3 个字节。); bw.newLine(); bw.close(); } }总结缓冲流就是给基础流加了一个 8KB 的内存缓冲区大幅减少磁盘 I/O 次数从而极大地提升读写效率。处理文本时首选BufferedReader和BufferedWriterreadLine()和newLine()会让你的代码极其优雅。

更多文章