文件复制

import java.io.*;

public class FileCopyHomework {

// 1. 复制文本文件:使用字符缓冲流
public static void copyTextFile(String srcPath, String destPath) {
try (BufferedReader reader = new BufferedReader(new FileReader(srcPath));
BufferedWriter writer = new BufferedWriter(new FileWriter(destPath))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // 每读一行,写一行并换行
}
System.out.println("✅ 文本文件复制成功!目标文件: " + destPath);
} catch (IOException e) {
System.out.println("❌ 文本文件复制失败: " + e.getMessage());
}
}

// 2. 复制任意文件:使用字节缓冲流
public static void copyAnyFile(String srcPath, String destPath) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath))) {
byte[] buffer = new byte[1024]; // 缓冲区 1KB
int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
System.out.println("✅ 任意文件复制成功!目标文件: " + destPath);
} catch (IOException e) {
System.out.println("❌ 任意文件复制失败: " + e.getMessage());
}
}

public static void main(String[] args) {
System.out.println("--- 开始测试 ---");

// 测试 1:复制文本
// 注意:在项目文件夹里先手动新建一个 "source.txt",里面随便写点汉字或英文
copyTextFile("source.txt", "dest_text.txt");

// 测试 2:复制图片/任意文件
// 注意:在项目文件夹里放一张图片,比如 "logo.jpg"
// 如果是电脑上没有的图片,可以自己找一张复制进去
copyAnyFile("logo.jpg", "dest_image.jpg");

System.out.println("--- 测试结束 ---");
}
}

245896d0eb1f9474e7d53b3445678fd5

1090e0e7fa0b01b62746fb6123d46fc1

posted on 2026-06-18 19:00  94hc  阅读(2)  评论(0)    收藏  举报