homework to blog 文件复制 IO 编程题

📅 2026/6/19 17:58:11
homework to blog 文件复制 IO 编程题
使用 Java IO 缓冲流完成两类文件复制功能字符缓冲流实现文本文件复制要求使用BufferedReader、BufferedWriter完成纯文本文件拷贝支持按行读取写入保证换行格式完整。仅适用于 txt、java 等文本文件。字节缓冲流实现任意文件万能复制要求使用BufferedInputStream、BufferedOutputStream可复制文本、图片、视频、压缩包等全部类型文件拷贝后文件可正常打开无损坏。代码import java.io.*;import java.util.Scanner;/**IO文件复制竞赛题字符缓冲流复制文本 字节缓冲流万能复制任意文件*/public class FileCopyHomeWork {public static void main(String[] args) {Scanner sc new Scanner(System.in);System.out.println(“ 文件复制工具 ”);System.out.println(“1.字符缓冲流仅复制文本文件”);System.out.println(“2.字节缓冲流万能复制所有文件”);System.out.print(“请输入选择”);int op sc.nextInt();sc.nextLine();System.out.print(输入源文件路径); String src sc.nextLine(); System.out.print(输入目标保存路径); String dest sc.nextLine(); try { if (op 1) { copyTextByCharBuffer(src, dest); System.out.println(文本复制完成); } else if (op 2) { copyAllFileByByteBuffer(src, dest); System.out.println(文件万能复制完成); } else { System.out.println(输入错误); } } catch (IOException e) { System.out.println(文件操作异常 e.getMessage()); } sc.close();}/**字符缓冲流只复制txt、java等纯文本*/public static void copyTextByCharBuffer(String srcPath, String destPath) throws IOException {// 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(); // 补全换行防止文本粘连}}}/**字节缓冲流万能复制图片、视频、压缩包、文本全部文件*/public static void copyAllFileByByteBuffer(String srcPath, String destPath) throws IOException {try (BufferedInputStream bis new BufferedInputStream(new FileInputStream(srcPath));BufferedOutputStream bos new BufferedOutputStream(new FileOutputStream(destPath))) {// 8KB缓冲区兼顾内存与读写效率byte[] buf new byte[1024 * 8];int len;while ((len bis.read(buf)) ! -1) {bos.write(buf, 0, len);}bos.flush(); // 强制刷新缓冲区防止残留数据丢失}}}心得体会本次文件复制作业让我分清了字符缓冲流与字节缓冲流的适用场景。字符缓冲流适合纯文本文件支持按行读取处理文字十分方便但不能复制图片、压缩包等二进制文件否则会损坏文件。字节缓冲流直接操作原始字节能万能复制所有类型文件通用性更强。缓冲流自带缓冲区相比基础文件流读写效率更高。同时我学会使用 try-with-resources 语法自动关闭流避免手动关闭遗漏导致资源占用。实操中我注意到两处易错点字符流复制要补换行符字节流写入需传入真实读取长度不能直接写入完整数组。这次练习让我掌握 IO 流选型规则处理文本用字符缓冲流通用文件拷贝用字节缓冲流做题时先判断文件类型再编写代码规避程序出错、文件损坏等问题规范了 IO 编程习惯。