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

}

结果

相关推荐
会编程的吕洞宾20 分钟前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤23 分钟前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha30 分钟前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
小飞在努力1 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
RobinXYuan1 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!1 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
CappuccinoRose2 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
tryCbest2 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
SimonKing2 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
CoderYanger3 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis