Java实现复制文件夹中指定文件

本文介绍了一个Java程序,该程序可以遍历指定目录及其子目录下的所有.jar文件,并将其复制到另一个目标目录。如果目标目录不存在,则会自动创建。若目标文件已存在,程序将覆盖原有文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        指定一个文件夹A,要将文件夹A下所有的后缀为".jar"的文件复制到文件夹B中。

package com.test;

import java.io.File;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class JavaTest
{
    public static void main(String[] args)
    {
        String sourceDirPath = "D:\\maven\\repo\\com\\lowagie";
        String targetDirPath = "D:\\test\\jars";
        copyJars(sourceDirPath, targetDirPath);
        System.out.println("复制完成!");
    }

    /**
     * 筛选.jar文件
     * @param sourceDirPath
     * @param targetDirPath
     * @throws Exception
     */
    private static void copyJars(String sourceDirPath, String targetDirPath)
    {
        try
        {

            File sourceDir = new File(sourceDirPath);
            if (!sourceDir.exists())
            {
                throw new Exception("目录不存在!" + sourceDirPath);
            }
            File targetDir = new File(targetDirPath);
            if (!targetDir.exists())
            {
                targetDir.mkdirs();
            }
            File[] subFiles = sourceDir.listFiles();
            for (File subFile : subFiles)
            {
                if (subFile.isDirectory())
                {
                    copyJars(subFile.getAbsolutePath(), targetDirPath);
                }
                else
                {
                    String name = subFile.getName();
                    // 判断文件后缀是否为.jar
                    if (name.endsWith(".jar"))
                    {
                        System.out.print("正在复制" + name + "...");
                        // 如果文件重名,则覆盖
                        Files.copy(Paths.get(subFile.getAbsolutePath()), Paths.get(targetDirPath + "/" + subFile.getName()),
                                   new CopyOption[] { StandardCopyOption.REPLACE_EXISTING });
                        System.out.println("[√]");
                    }
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值