指定一个文件夹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();
}
}
}