代码:
package com.io.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class copyDir { public static void main(String[] args) { copyDir("d:/a","d:/b"); } /** * 复制文件夹 */ private static void copyDir(String srcRoot,String srcDir,String destDir){ if(srcRoot == null){ srcRoot = srcDir ; } //源文件夹 File srcFile = new File(srcDir); //目标文件夹 File destFile = new File(destDir); //判断srcFile有效性 if(srcFile == null || !srcFile.exists()){ return ; } //创建目标文件夹 if(!destFile.exists()){ destFile.mkdirs(); } //判断是否文件? if(srcFile.isFile()){ String absPath = srcFile.getAbsolutePath() ; //取出上级目录 d: String parentDir = new File(srcRoot).getParent(); //取出相对的路径 String relPath = absPath.substring(parentDir.length()); File destFile2 = new File(destDir,relPath); //拷贝文件 copyFile(srcRoot,srcFile.getAbsolutePath(),destDir); } //目录 else{ File[] children = srcFile.listFiles(); if(children != null){ for(File f : children){ copyDir(srcRoot,f.getAbsolutePath(),destDir); } } } } public static void copyDir(String srcDir,String destDir){ copyDir(srcDir,srcDir,destDir); } /** * 复制文件 */ public static void copyFile(String srcRoot,String path,String destDir){ try { //准备目录 //取出相对的路径 String tmp = path.substring(srcRoot.length()); String folder = new File(destDir,tmp).getParentFile().getAbsolutePath(); System.out.println(folder); File destFolder = new File(folder); destFolder.mkdirs(); File f = new File(path); //fis FileInputStream fis = new FileInputStream(path); String newDestpath = null ; //文件输出流 FileOutputStream fos = new FileOutputStream(new File(destFolder,new File(path).getName())); //流的对拷贝 byte[] buf = new byte[1024] ; int len = 0 ; while((len = fis.read(buf)) != -1){ fos.write(buf, 0, len); } fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } }