public static void main(String[] args) throws IOException { //指定数据源 File srcPath = new File("E:\\新建文件夹 (2)"); //指定目的地 File destPath = new File("E:\\新建文件夹(4)"); //复制文件夹 fuzhiwenjianjia(srcPath,destPath); } //复制文件夹 private static void fuzhiwenjianjia(File srcPath, File destPath) throws IOException { //创建目的地文件夹 destPath.mkdir(); //获取数据源中所有的File对象 File[] files = srcPath.listFiles();//获取目录下的所有文件和文件夹, 封装成数组 //遍历,得到每一个File对象 for (File file : files) { //判断当前File对象是否为文件夹 //isDirectory()判断是不是文件夹 if(file.isDirectory()){ File dest = new File(destPath,file.getName()); //进去子文件夹,递归回到复制文件夹 fuzhiwenjianjia(file,dest); }else{ File dest = new File(destPath,file.getName()); //调用复制文件的方法 fuzhiwenjian(file,dest); } } } private static void fuzhiwenjian(File file, File dest) throws IOException { //指定数据源 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); //指定目的地 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest)); //创建字节数组 byte[] buffer = new byte[1024]; int len = -1; //读取 while((len = bis.read(buffer)) != -1){ //写入 bos.write(buffer, 0, len); } //关闭流 bis.close(); bos.close(); } |