目录
前言
一、字节缓冲流
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:\r;Windows:\r\n;Linux:\n |
1.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:\r;Windows:\r\n;Linux:\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和BufferedWriter,readLine()和newLine()会让你的代码极其优雅。