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);
        }
    }

}

结果

相关推荐
IT研究室几秒前
最新计算机毕业设计选题推荐-基于spring boot的幼儿园管理系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
会编程的吕洞宾2 分钟前
Spring Cloud Gateway限流实战 Redis令牌桶算法+熔断降级
java·后端·spring
zx_741484819 分钟前
PyQt5 环境搭建保姆级教程:PyCharm + QtDesigner + PyUIC 完整配置
开发语言·qt·pycharm·pyqt
Wang's Blog14 分钟前
Java 项目部署之 Docker工具快速入门: DockerCompose 部署微服务集群
java·docker·微服务
BullSmall26 分钟前
SonarQube 9.9.8-community 适配 Jenkins 版本说明
java·前端·jenkins
威哥爱编程27 分钟前
【AI全栈12-10】Spring Boot 用多模态做商品图审核 / 发票识别
java·spring boot·后端
Soari30 分钟前
交换机转发模式
开发语言·网络·php
轮子大叔35 分钟前
Java8和Java17常见区别
java
威哥爱编程36 分钟前
【AI全栈12-09】Spring Boot 用流式输出做打字机对话:点下去不再干等
java·spring boot·后端
威哥爱编程39 分钟前
【AI全栈12-08】Spring Boot 用 MCP 统一接入内部系统:让 AI 接一次,全公司复用
java·spring boot·后端