本文目录导读:

在Java中,缓冲流(Buffered Stream)通过在内存中创建一个缓冲区,减少实际的I/O操作次数,从而显著提高读写性能,下面是缓冲流读写的完整案例。
基本概念
- BufferedInputStream:字节缓冲输入流
- BufferedOutputStream:字节缓冲输出流
- BufferedReader:字符缓冲输入流
- BufferedWriter:字符缓冲输出流
完整代码案例
使用字节缓冲流复制文件
import java.io.*;
public class BufferedStreamExample {
public static void main(String[] args) {
// 源文件和目标文件路径
String sourceFile = "source.txt";
String destFile = "dest.txt";
// 使用try-with-resources自动关闭资源
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile))) {
// 定义缓冲区大小(默认8192字节)
byte[] buffer = new byte[1024];
int bytesRead;
// 读取数据并写入
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
// 注意:不用手动flush,close时会自动flush
}
System.out.println("文件复制成功!");
} catch (FileNotFoundException e) {
System.err.println("文件未找到: " + e.getMessage());
} catch (IOException e) {
System.err.println("IO异常: " + e.getMessage());
}
}
}
使用字符缓冲流读写文本文件
import java.io.*;
public class BufferedWriterReaderExample {
public static void main(String[] args) {
// 1. 写入文件
writeFile("output.txt");
// 2. 读取文件
readFile("output.txt");
}
// 使用BufferedWriter写入文件
public static void writeFile(String filename) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
// 写入内容
bw.write("Java缓冲流案例");
bw.newLine(); // 写入换行符
bw.write("使用BufferedWriter写入");
bw.newLine();
bw.write("提高IO性能");
// 手动刷新缓冲区(可选,close时会自动调用)
bw.flush();
System.out.println("写入完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
// 使用BufferedReader读取文件
public static void readFile(String filename) {
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
System.out.println("\n读取文件内容:");
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
带缓冲区和进度提示的大文件复制
import java.io.*;
public class LargeFileCopy {
public static void main(String[] args) {
String source = "largefile.dat";
String target = "copy_largefile.dat";
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target))) {
// 使用更大的缓冲区提高性能
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
long totalBytes = 0;
long startTime = System.currentTimeMillis();
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
// 每读取10MB显示一次进度
if (totalBytes % (1024 * 1024 * 10) == 0) {
System.out.println("已复制: " + (totalBytes / (1024 * 1024)) + " MB");
}
}
long endTime = System.currentTimeMillis();
System.out.println("复制完成!总大小: " + (totalBytes / (1024 * 1024)) + " MB");
System.out.println("耗时: " + (endTime - startTime) + " 毫秒");
} catch (IOException e) {
e.printStackTrace();
}
}
}
性能对比演示
import java.io.*;
public class PerformanceComparison {
public static void main(String[] args) throws IOException {
String testFile = "test.txt";
createTestFile(testFile, 100 * 1024 * 1024); // 创建100MB测试文件
// 测试普通流
long time1 = testWithoutBuffer(testFile);
System.out.println("无缓冲耗时: " + time1 + " ms");
// 测试缓冲流
long time2 = testWithBuffer(testFile);
System.out.println("带缓冲耗时: " + time2 + " ms");
System.out.println("性能提升: " + (time1 / (double)time2) + " 倍");
}
// 创建测试文件
private static void createTestFile(String filename, long size) throws IOException {
try (FileOutputStream fos = new FileOutputStream(filename)) {
byte[] data = new byte[1024]; // 1KB块
for (int i = 0; i < size / data.length; i++) {
fos.write(data);
}
}
}
// 无缓冲读取
private static long testWithoutBuffer(String filename) throws IOException {
long start = System.currentTimeMillis();
try (FileInputStream fis = new FileInputStream(filename)) {
int data;
while ((data = fis.read()) != -1) {
// 模拟处理
}
}
return System.currentTimeMillis() - start;
}
// 带缓冲读取
private static long testWithBuffer(String filename) throws IOException {
long start = System.currentTimeMillis();
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename))) {
int data;
while ((data = bis.read()) != -1) {
// 模拟处理
}
}
return System.currentTimeMillis() - start;
}
}
关键要点
缓冲区大小说明
- 默认缓冲区大小:8192字节(8KB)
- 可以自定义:
new BufferedInputStream(in, 16384)
重要方法
flush():手动刷新缓冲区readLine():BufferedReader特有的按行读取newLine():BufferedWriter的跨平台换行
注意事项
- 资源关闭:使用try-with-resources自动关闭
- 一个流包装:缓冲区流必须包装在其他流上
- 性能选择:对于大文件处理,缓冲流性能优势明显
- 手动刷新:在需要实时写入时调用flush()
运行结果示例
写入完成!
Java缓冲流案例
使用BufferedWriter写入
提高IO性能
缓冲流是Java IO性能优化的基础工具,掌握它们对于处理文件操作非常重要。