2026.05.22

IO 流是 Java 基础中的重点,也是竞赛和面试的高频考点。今天我们就来搞定两个最常见的文件复制问题:文本文件复制和任意文件复制,分别用字符缓冲流和字节缓冲流实现。

一、文本文件复制:字符缓冲流(最常用)

字符流(Reader/Writer)专门处理文本文件,缓冲流(BufferedReader/BufferedWriter)自带缓冲区,效率高,还支持按行读写,是文本处理的首选。

示例:文本文件复制

import java.io.*;

public class TextCopy {

    public static void main(String[] args) {

        // 定义源文件路径、目标复制文件路径

        String srcPath = "source.txt";

        String destPath = "target.txt";

        // try-with-resources 自动关闭流,避免资源泄漏

        try (BufferedReader br = new BufferedReader(new FileReader(srcPath));

             BufferedWriter bw = new BufferedWriter(new FileWriter(destPath))) {

            String line;

            // 按行读取文本(readLine 不读取换行符)

            while ((line = br.readLine()) != null) {

                bw.write(line);

                bw.newLine(); // 补充换行符,保证文件格式一致

            }

            System.out.println("文本文件复制完成!");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

二、任意文件复制:字节缓冲流(万能复制)

字节流(InputStream/OutputStream)以字节为单位读写,能处理所有类型的文件(文本、图片、视频、音频等),搭配缓冲流效率更高。

示例:任意文件复制

import java.io.*;

public class AnyFileCopy {

    public static void main(String[] args) {

        // 可替换为图片、视频、音频、压缩包等任意文件

        String srcPath = "source.jpg";

        String destPath = "target.jpg";

        // 字节缓冲流实现高效复制

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));

             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))) {

            // 定义 1024 字节缓冲区,批量读写

            byte[] buffer = new byte[1024];

            int len;

            // 循环读取文件,len = -1 表示读取到文件末尾

            while ((len = bis.read(buffer)) != -1) {

                // 只写入本次读取到的有效字节数据

                bos.write(buffer, 0, len);

            }

            System.out.println("任意文件复制完成!");

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

三、两种复制方式的对比

复制方式 适用场景 优点 缺点
字符缓冲流 文本文件(.txt/.java/.md) 处理中文友好,支持按行读写,效率高 不能处理非文本文件
字节缓冲流 所有类型文件(文本 / 图片 / 视频) 万能复制,无乱码问题,效率高 不支持按行读写,文本文件处理不如字符流直观

文本文件复制用字符缓冲流,任意文件复制用字节缓冲流,这是 Java IO 流竞赛题的核心考点。掌握这两种写法,文件复制类题目就能轻松搞定。

更多推荐