package com.homework2; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class CopyUtils { //複製文件 public static void copyFile(File srcFile,File desFile) throws Exception{ InputStream in=new FileInputStream(srcFile); OutputStream os=new FileOutputStream(desFile); byte []a =new byte[1024]; int len=-1; while((len=in.read(a))!=-1){ os.write(a, 0, len); } in.close(); os.close(); } /*複製文件或者目錄 * sourFile存在,desFile不存在。 建立desFile對象。 sourFile不存在,desFile存在或者desFile不存在 返回方法,不用操做 sourFile存在,desFile存在. --進行操做。 */ public static void copy(File sourFile, File desFile) throws Exception { if(!sourFile.exists()){ return; } if(sourFile.exists()&&!desFile.exists()){ desFile.mkdirs(); } // sourFile存在,desFile存在。 File []files=sourFile.listFiles(); //遍歷 for(File f:files){ //建立目錄或者文件。 File file=new File(desFile,f.getName()); // 子目錄有多是文件夾 if(f.isDirectory()){ file.mkdirs(); // 遞歸 copy(f, file); }else{ file.createNewFile(); copyFile(f, file); } } } //將指定目錄的.java或者.xml轉換爲.txt文件。而且將目錄也複製過去 public static void switchFile(File sourFile,File desFile) throws Exception{ if (!sourFile.exists()) { return; } if (sourFile.exists() && !desFile.exists()) { desFile.mkdirs(); } //源路徑和目的路徑都是存在的。 File []files=sourFile.listFiles(); //遍歷 for(File f :files){ if(f.isDirectory()){ File file = new File(desFile,f.getName()); file.mkdir(); switchFile(f, file); }else{ String name=f.getName(); if(name.endsWith(".java")||name.endsWith(".xml")){ String filename=name.substring(0, name.lastIndexOf(".")); File file=new File(desFile, filename+".txt"); copyFile(f, file); } } } } //格式化輸出目錄。 public static void print(File file,int length){ if(!file.exists()){ return; } //目錄存在。 if(file.isDirectory()){ //文件夾。 File[] files = file.listFiles(); length++; System.out.println(printDraw(length)+file.getName()); for(File f:files){ //文件夾或者文件。 //遞歸 print(f,length); } }else{ System.out.println(printDraw(length)+file.getName()); } } //打印出圖形。 public static String printDraw(int length){ StringBuilder sb = new StringBuilder(); for(int i=0;i<length;i++){ sb.append("|--"); } return sb.toString(); } } 測試類: package com.homework2; import java.io.File; import java.util.Scanner; public class CopyUtilsTest { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); System.out.println("輸入第一個地址:"); String path1 = in.nextLine(); File file1 = new File(path1); System.out.println("輸入第二個地址:"); String path2 = in.nextLine(); File file2 = new File(path2); CopyUtils.switchFile(file1,file2); /* CopyUtils.print(file1,0);*/ } }