Java 文件复制(字符 / 字节缓冲流)
一、核心概念
Java 文件复制,本质就是把文件数据从一个流读到内存,再从内存写到另一个流。根据文件类型不同,我们用两种不同的流:
字符缓冲流(BufferedReader/BufferedWriter):专门处理文本文件(.txt/.java/.md 等),最常用。
字节缓冲流(BufferedInputStream/BufferedOutputStream):万能复制,支持所有文件(文本、图片、视频、音频等)。
二、文本文件复制(字符缓冲流)
适合场景:纯文本文件,效率比普通字符流高很多。
代码示例
import java.io.*; public class TextCopy { public static void main(String[] args) { // 源文件路径 String srcPath = "src/original.txt"; // 目标文件路径 String destPath = "src/copy.txt"; // 用try-with-resources自动关闭流 try ( BufferedReader br = new BufferedReader(new FileReader(srcPath)); BufferedWriter bw = new BufferedWriter(new FileWriter(destPath)) ) { String line; // 按行读取文本 while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); // 换行,还原原文件格式 } System.out.println("文本文件复制完成!"); } catch (IOException e) { e.printStackTrace(); } } }三、任意文件复制(字节缓冲流,万能复制)
适合场景:所有类型文件,尤其是非文本文件(图片、视频、压缩包等)。
代码示例
import java.io.*; public class AnyFileCopy { public static void main(String[] args) { String srcPath = "src/original.jpg"; String destPath = "src/copy.jpg"; try ( BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath)) ) { byte[] buffer = new byte[1024]; // 缓冲数组,一次读1KB int len; while ((len = bis.read(buffer)) != -1) { bos.write(buffer, 0, len); } System.out.println("文件复制完成!"); } catch (IOException e) { e.printStackTrace(); } } }四、两种方式对比
| 方式 | 适用文件 | 优点 | 缺点 |
|---|---|---|---|
| 字符缓冲流 | 纯文本文件 | 读取方便(按行读)、性能高 | 只能处理文本,不能复制图片 / 视频 |
| 字节缓冲流 | 所有文件(万能) | 兼容性强,任何文件都能复制 | 读取的是字节,处理文本时不如字符流方便 |
五、关键知识点
1.缓冲流的作用:自带缓冲区,减少磁盘 IO 次数,大幅提升复制效率,比普通 FileInputStream/FileReader 快很多。
2.try-with-resources:自动关闭流,避免手动写 finally 代码,更安全简洁。
r3.eadLine () 和缓冲数组:字符流用 readLine () 按行读文本;字节流用 byte [] 数组批量读数据,减少 IO 次数。
六、一句话总结
复制文本文件:用字符缓冲流,简单高效。
复制任意文件:用字节缓冲流,兼容性强,是 “万能复制器”。
