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

}

结果

相关推荐
豐儀麟阁贵9 分钟前
8.1 异常概述
java·开发语言
czhc114007566324 分钟前
C# 1124 接收
开发语言·c#
qq_12498707531 小时前
基于springboot的疾病预防系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·毕业设计
麦烤楽鸡翅1 小时前
简单迭代法求单根的近似值
java·c++·python·数据分析·c·数值分析
火星数据-Tina1 小时前
低成本搭建体育数据中台:一套 API 如何同时支撑比分网与 App?
java·前端·websocket
lcu1111 小时前
Java 学习38:ArrayList 类
java
q***2512 小时前
Spring Boot 集成 Kettle
java·spring boot·后端
筱顾大牛2 小时前
IDEA使用Gitee来创建远程仓库
java·gitee·intellij-idea
司铭鸿2 小时前
祖先关系的数学重构:从家谱到算法的思维跃迁
开发语言·数据结构·人工智能·算法·重构·c#·哈希算法
懂得节能嘛.2 小时前
【SDK开发实践】从Java编码到阿里云制品仓库部署
java·阿里云·maven