public class CopyFiles { public static void main(String[] args) throws Exception { String src = "C:\\Users\\Administrator\\Desktop\\java\\workspace\\Day01\\sources\\a";//源路径 String tar = src+1; //目标路径 copyFolder(src,tar); //拷贝文件夹方法 } private static void copyFolder(String srcFolder, String tarFolder) throws Exception { File tar = new File(tarFolder); if(!tar.exists()){ tar.mkdir(); } //System.out.println(tar.getName()); File src = new File(srcFolder); File[] srcFiles = src.listFiles();//遍历源文件 for (File file:srcFiles ) { if(file.isFile()){//如果是文件则拷贝 //System.out.println(file.getName()); // System.out.println("拷贝文件"); String tarPath = tarFolder+"\\"+file.getName(); // System.out.println(tarName); copyFile(file,tarPath); } else {//如果不是文件,则新建文件夹,把当前文件拷贝到文件夹 // System.out.println("拷贝文件夹"); //新建文件夹 // System.out.println(file.getName()); String tarPath = tarFolder+"\\"+file.getName(); copyFolder(file.getAbsolutePath(),tarPath); } } } private static void copyFile(File srcFile, String tarPath) throws Exception { FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(tarPath); int len = 0; byte[] temp = new byte[1024]; while((len=in.read(temp))!=-1){ out.write(temp,0,len); out.flush(); } out.close(); in.close(); } }
原文:https://www.cnblogs.com/5aixin/p/11443834.html