基本思路就是边搜索边复制,这里用的是广度搜索(BFS)
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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; import java.util.ArrayDeque; public class CopyFile { public static void main(String[] args) { File f1 = new File("kkk"); File f2 = new File("D:\"); try { getPathBFS(f1,f2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 用于读和写 * @param f1 输入流 * @param f2 输出流 */ private static void copyFile(File f1,String f2){ InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(f1)); out = new BufferedOutputStream(new FileOutputStream(f2)); byte by[] = new byte[1024]; int len = 0; while((len = in.read(by))!=-1){ out.write(by, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(in!=null){ try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(out != null){ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 用于搜索 * @param f1 目标文件 * @param f2 复制到的目标 * @throws IOException */ private static void getPathBFS(File f1,File f2) throws IOException { //运用队列进行广度搜索 ArrayDeque<File> deque = new ArrayDeque<File>(); //用于存储复制目标文件 ArrayDeque<File> dequeCopy = new ArrayDeque<File>(); //第一个File实例入队 deque.offer(f1); //创建第一个文件夹 f2 = new File(f2,f1.getName()); dequeCopy.offer(f2); //队列为空时停止 while(!deque.isEmpty()){ //取队头 File[] ff = deque.peek().listFiles(); File copyFiledir = dequeCopy.peek(); //创建文件夹 copyFiledir.mkdir(); //出队 deque.poll(); dequeCopy.poll(); for(int i=0;i<ff.length;i++){ //如果是目标文件夹入队 if(ff[i].isDirectory()){ //复制文件夹入队 File temp = new File(copyFiledir,ff[i].getName()); dequeCopy.push(temp); deque.push(ff[i]); }else{ //复制到相应文件夹 copyFile(ff[i],copyFiledir.getAbsolutePath()+"\"+ff[i].getName()); } } } } }