Here you can find the source of copyDir(String sourceDir, String targetDir)
Parameter | Description |
---|---|
sourceDirOrFile | a parameter |
targetDirOrFile | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static void copyDir(String sourceDir, String targetDir) throws IOException
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.IOException; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; public class Main { /**/*from www . j a v a 2 s . c o m*/ * copy files from directory sourceDirOrFile to directory targetDirOrFile * @param sourceDirOrFile * @param targetDirOrFile * @throws IOException */ public static void copyDir(String sourceDir, String targetDir) throws IOException { File sDir = new File(sourceDir); File tDir = new File(targetDir); if (!tDir.exists()) { tDir.mkdirs(); } if (sDir.exists()) { if (sDir.isDirectory()) { File[] files = sDir.listFiles(); for (File listfile : files) { if (listfile.isFile()) { String filename = listfile.getName(); String targetFile = tDir.getCanonicalPath() + File.separator + filename; copyFile(listfile.getAbsolutePath(), targetFile); } else if (listfile.isDirectory()) { String sourceDirectory = listfile.getCanonicalPath(); String dirname = listfile.getName(); String targetDirectory = tDir.getCanonicalPath() + File.separator + dirname; copyDir(sourceDirectory, targetDirectory); } } } } else { System.err.println("Copy from " + sourceDir + " to " + targetDir + " error!"); } } /** * list all files in the dir * @param dir * @return */ public static List<File> listFiles(String dir) { List<File> files = new ArrayList<>(); File file = new File(dir); if (file.exists() && file.isDirectory()) { File[] fs = file.listFiles(); for (File f : fs) { files.add(f); } } else { System.err.println("Dir " + dir + " doesn't exist or is not directory!"); } return files; } /** * copy file sourceFile to targetFile * @param sourceFile * @param targetFile * @throws IOException */ public static void copyFile(String sourceFile, String targetFile) throws IOException { Path fromFile = Paths.get(sourceFile); Path toFile = Paths.get(targetFile); CopyOption[] options = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES }; Files.copy(fromFile, toFile, options); } }