Java—文件拷贝

将指定的文件或目录拷贝到指定目录夹下

java 复制代码
import java.io.*;
import java.util.Scanner;

/**
 * 实现一个文件拷贝
 */
public class FileCopy {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要拷贝的源文件路径:");
        String srcPath = scanner.next();
        System.out.println("请输入要拷贝的目标文件路径:");
        String destPath = scanner.next();
        File src = new File(srcPath);
        File dest = new File(destPath);
        process(src,dest);
        System.out.println("拷贝完成!!!");
    }

    /**
     * 进行文件拷贝
     * @param src 源文件
     * @param dest 目标文件
     */
    public static void process(File src, File dest)  {
        // 判断源文件是否为文件
        if(src.isFile()){
            // 将源文件直接拷贝到目标文件夹下
            try(
                    FileInputStream fileInputStream = new FileInputStream(src);
                    FileOutputStream fileOutputStream = new FileOutputStream(dest +"\\" + src.getName() );
            ){
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len = fileInputStream.read(bytes)) != -1){
                    fileOutputStream.write(bytes, 0, len);
                }
                fileOutputStream.flush();
            }catch (IOException e){
                System.out.println("出错了!!!");
            }
            // 结束递归
            return;
        }
        // 执行到这里说明不是文件,是目录
        File newFile = new File(dest.getPath() + "\\" + src.getName());
        if(!newFile.exists()){
            newFile.mkdirs();
        }
        // 得到目录下的所有文件
        File[] files = src.listFiles();
        for (File file : files) {
            process(file, newFile);
        }
    }

}

结果

相关推荐
CoderIsArt4 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
微尘寒风4 小时前
【Git】的安装和使用
java·git
y = xⁿ5 小时前
DeepSeek Harness 学习日记:关于Agent接口,工具调用的底层实现
android·java·学习
侧耳倾听1115 小时前
jwt使用简介
java·jwt
顶点多余6 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
AI人工智能+电脑小能手6 小时前
大白话说Java设计模式-46-责任链模式(业务实战篇)
java·设计模式·责任链模式·风控校验·servlet filter·spring interceptor·链式处理
jay神6 小时前
【计算机毕业设计】基于SpringBoot的程序教学辅助系统
java·前端·vue.js·spring boot·后端·毕业设计·课程设计
AI情绪识别开源6 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
2601_962066497 小时前
【Sql Server】Update中的From语句,以及常见更新操作方式
android·java·数据库