import java.io.*; import java.util.Scanner; public class Demo { public static void main(String[] args) { File srcDirFile = getDirFile("输入源文件夹路径"); File destDirFile = getDirFile("输入目标路径"); if (srcDirFile.equals(destDirFile)) { System.out.println("源文件夹和目标文件夹相同,不能复制"); return; } try { copyDirFile(srcDirFile, destDirFile); } catch (Exception e) { e.printStackTrace(); } } /** * 复制 * * @param srcDirFile * @param destDirFile */ private static void copyDirFile(File srcDirFile, File destDirFile) throws Exception { File file = new File(destDirFile, srcDirFile.getName()); file.mkdir(); File[] srcListFiles = srcDirFile.listFiles(); for (File subFile : srcListFiles) { if (subFile.isFile()) { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(file, subFile.getName()))); int len; while ((len = bis.read()) != -1) { bos.write(len); } bis.close(); bos.close(); } else { copyDirFile(subFile, file); } } } /** * 获取文件夹路径 */ private static File getDirFile(String msg) { Scanner scanner = new Scanner(System.in); System.out.println(msg); while (true) { String line = scanner.nextLine(); File file = new File(line); if (file.isDirectory()) { return file; } else { System.out.println("输入错误,重新输入"); } } } }
标签:srcDirFile,Java,File,递归,destDirFile,文件夹,file,new From: https://www.cnblogs.com/Big-Boss/p/18086141