複製和替換工具類: package com.homework; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class CopyUtil { public static void Copy(File srcFile, File desFie,String before,String after ) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(srcFile); os = new FileOutputStream(desFie + File.separator + srcFile.getName().replace(before, after)); byte[] a = new byte[1024]; int len = -1; while ((len = is.read(a)) != -1) { os.write(a, 0, len); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { is.close(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void Copy(File srcFile, File desFie ) {//若是不用替換後綴的話,在控制檯輸入源目錄和目標目錄便可 InputStream is = null; OutputStream os = null; try { is = new FileInputStream(srcFile); os = new FileOutputStream(desFie + File.separator + srcFile.getName()); byte[] a = new byte[1024]; int len = -1; while ((len = is.read(a)) != -1) { os.write(a, 0, len); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { is.close(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } 主程序測試類: package com.homework; import java.io.File; import java.util.Scanner; /*複製當前目錄。 將指定目錄的.java或者.xml轉換爲.txt文件。而且將目錄也複製過去。 遍歷指定目錄的全部文件,而且格式化打印出文件的名字。*/ public class CopyOtherTest { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("--請輸入源目錄---"); String source = scanner.nextLine(); System.out.println("--請輸入目標目錄---"); String destination = scanner.nextLine(); System.out.println("--請輸入變換前的後綴---"); String before = scanner.nextLine(); System.out.println("--請輸入要改後的後綴---"); String after = scanner.nextLine(); File srcFile = new File(source); File desFie = new File(destination); try { Find(srcFile, desFie,before,after); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void Find(File srcFile, File desFie, String before, String after) { if (!srcFile.exists()) { return; } if (srcFile.isFile()) { if (!desFie.exists()) { desFie.mkdirs(); } System.out.println("------"+srcFile.getPath()); if (srcFile.getName().endsWith(before)) { CopyUtil.Copy(srcFile,desFie,before,after); }else{ CopyUtil.Copy(srcFile,desFie); } } else if (srcFile.isDirectory()) { File[] file = srcFile.listFiles(); System.out.println("當前目錄:"+srcFile.getAbsolutePath()); for (File f : file) { Find(f, new File(desFie + File.separator + srcFile.getName()),before,after); } } } }