按你的要求写了一个
- /*
- 需求:
- 将指定目录下所有.java文件拷贝到另一个目录中,并将扩展名改为.txt
- */
- import java.io.*;
- import java.util.*;
- class FileCopy
- {
- public static void main(String[] args)
- {
- File src = new File("D:\\test\\JavaTest");//指定目标文件夹
- File des = new File("D:\\test\\copy");//指定目的文件夹
- copyToTxt(src,".java",des);
- }
- public static void copyToTxt(File src,String key,File des)
- {
- if (!des.exists())
- des.mkdir();//如果目的文件夹不存在则创建目录
- ArrayList<File> al = new ArrayList<File>();
- fileFilter(src,key,al);//过滤目标文件夹,将符合要求的文件添加到集合中
- for(File file:al)
- {
- System.out.println("File:"+file+"...copy:"+copyFile(file,key,des));//遍历集合,复制文件
- }
- }
- public static void fileFilter(File src,final String key,ArrayList<File> al)//过滤文件
- {
- File[] list = src.listFiles(new FileFilter()
- {
- //定义过滤器,返回目录和以key结尾的文件
- public boolean accept(File pathname)
- {
- if (pathname.isDirectory())
- return true;
- else
- return pathname.getName().endsWith(key);
- }
- });
- for(File f:list)
- {
- if (f.isDirectory())
- fileFilter(f,key,al);//若是目录则递归
- else
- {
- al.add(f);//将过滤后的文件添加进指定集合
- }
- }
- }
- public static boolean copyFile(File file,String key,File des)//复制文件
- {
- BufferedReader bufr = null;
- BufferedWriter bufw = null;
- try
- {
- bufr = new BufferedReader(new FileReader(file));
- bufw = new BufferedWriter(new FileWriter(new File(des,file.getName().replace(key,".txt"))));//用.txt替换key
- String line = null;
- while ((line=bufr.readLine())!=null)
- {
- bufw.write(line);
- bufw.newLine();
- bufw.flush();
- }
- return true;
- }
- catch (IOException e)
- {
- throw new RuntimeException("复制失败");
- }
- finally
- {
- try
- {
- if(bufr!=null)
- bufr.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("流关闭失败");
- }
- try
- {
- if(bufw!=null)
- bufw.close();
- }
- catch (IOException e)
- {
- throw new RuntimeException("流关闭失败");
- }
- }
- }
- }
复制代码 |