下面是Java代码实现:

import java.io.*;

public class FileCopy {
    public static void main(String[] args) {
        try {
            // 创建两个文件夹
            File dir1 = new File("D:/img1");
            File dir2 = new File("D:/img2");
            dir1.mkdir();
            dir2.mkdir();

            // 在img1中放置一个图片文件
            File file1 = new File("D:/img1/image.jpg");
            if (!file1.exists()) {
                file1.createNewFile();
            }

            // 将img1中的图片文件使用字节流复制到img2中
            File file2 = new File("D:/img2/image_copy.jpg");
            FileInputStream fis = new FileInputStream(file1);
            FileOutputStream fos = new FileOutputStream(file2);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
            System.out.println("文件复制完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项:

  1. 需要在try-catch块中处理IOException异常;
  2. 在创建文件夹和文件之前需要判断是否已经存在,避免重复创建;
  3. 在使用字节流复制文件时要注意缓冲区大小,一次读取的字节数最好设置为1024或者其倍数;
  4. 使用完流之后需要关闭,否则可能会造成资源泄漏
使用io流完成在D盘中创建两个文件夹img1img2。在img1中放置一个图片文件将img1中的图片文件使用字节流复制到img2中。

原文地址: https://www.cveoy.top/t/topic/frPj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录