package com.obcy; import java.io.*; import java.util.Scanner; public class Search { private static Search search = new Search(); private String source = "" ; private String target = ""; private String type = ""; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入你要遍历的目录(绝对路径)"); search.source = sc.nextLine(); System.out.println("请输入你要挑选的文件类型(文件后缀名)"); search.type = sc.nextLine(); System.out.println("你要将这种类型的文件复制到哪(结对路径)"); search.target = sc.nextLine(); System.out.println("startting"); getAllPath(new File(search.source)); } //此功能遍历allpath集合,并把string对象拆分,取到所有的文件类型 private static String getPathTail(String filename) { String[] split = filename.split("\\."); return split[split.length-1]; } //复制文件方法 public void cp(String input,String output) throws IOException { File in = new File(input) ; File dir = new File(output); if(!dir.exists()){ if(dir.mkdirs()){ System.out.println("已创建目录"+dir.getAbsolutePath()); }else{ System.out.println("目录创建失败"); return; } } System.out.println(in.getName()+"正在复制"); File out = new File(dir,in.getName()); FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); BufferedInputStream bfin = new BufferedInputStream(fin); BufferedOutputStream bfout = new BufferedOutputStream(fout); int len = 0; byte[] bt = new byte[4096]; while ((len = fin.read(bt))!=-1){ fout.write(bt,0,len-1); } System.out.println(in.getName()+"复制完成"); fin.close(); fout.close(); bfin.close(); bfout.close(); } //递归遍历到文件夹下所有的文件,并存储到ArrayList数组内 private static void getAllPath(File path) { if (path.exists()) { //判断路径是否存在 if (path.isFile()) { //判断是不是文件,是的话,得到其文件名。不是的话,就是目录 String absolutePath = path.getAbsolutePath(); String tail = getPathTail(absolutePath); //获取文件类型 if(search.type.equals(tail)){ try { search.cp(absolutePath,search.target); } catch (IOException e) { e.printStackTrace(); } } }else{ File[] files = path.listFiles(); //得到目录下所有的Fiel列表 if (files!=null) { //如果目录列表不为零,递归操作此列表里所有路径 for (File file : files) { getAllPath(file); } } } }else{ System.out.println("文件路径不存在"); } } }