package cn.day23; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class test { public static void main(String[] args) { File f = new File("D:\\1"); String s = "D:\\2"; fofile(f, s); } /* * 遍历源路劲文件夹中所有文件 * 1.转化为File【】数组 * 2.遍历 * 3.调用copy方法 */ public static void fofile(File f,String s){ File[] file = f.listFiles(); for(File fi : file){ if(fi.isDirectory()){ new File(s+ "\\" + fi.getName()).mkdirs(); String news = s+ "\\" + fi.getName(); fofile(fi,news); }else{ String fs = fi.getName(); copy(fi, s+ "\\" +fs); }} } /** * @param args * 1.从键盘接收两个文件夹路径,把其中一个文件夹中(包含内容)拷贝到另一个文件夹中 * copy方法 */ public static void copy(File fi1,String fo1) { FileInputStream fi = null; FileOutputStream fo = null; try{ fi = new FileInputStream(fi1); fo = new FileOutputStream(fo1); int len = 0; byte[] by = new byte[1024]; while((len = fi.read(by)) != -1){ fo.write(by, 0, len); } }catch(IOException ex){ ex.printStackTrace(); throw new RuntimeException(); }finally{ try{ if(fo != null) fo.close(); }catch(IOException exception){ throw new RuntimeException(); }finally{ try { if(fi != null) fi.close(); } catch (Exception e) { // TODO: handle exception } } } } }