July 10, 2021

How to Copy a Directory in Java

This post shows how to copy a directory in Java where all the files and sub folders with in a directory are recursively copied to a new directory.

Options for copying a directory in Java

For copying the folder tree structure which includes the sub-directories and all the files you can use one of the following options in Java-

  • Using File.listFiles() method which returns an array of abstract pathnames denoting the files in the directory. Then you can iterate the array to list the files and copy them to the target directory, you will have to recursively call your method to list files with in the sub-directories. See example.
  • Java 7 onward you can use Files.walkFileTree method which walks a file tree rooted at a given starting file. See example.
  • Java 8 onward you can use Files.walk() method which returns the Path objects as stream by walking the file tree rooted at a given starting file. See example.

Directory structure used

Java programs shown here to copy a directory in Java use the following directory structure.

copy a folder in Java

With in the parent folder there is one sub folder Child with two files and one file is stored in the parent folder.

Copying directory in Java using Files.walk() method

Java 8 onward You can use Files.walk() method which returns the Path objects as stream. Each path in that Stream can be checked then to verify whether it's a directory or a file. If it is a file, it has to be copied to the target location, in case of directory you need to create that directory at the target location.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class CopyDirectory {
  public static void main(String[] args) {
    final String SOURCE_DIR = "F:/knpcode/Parent";
    final String TARGET_DIR = "F:/knpcode/Parent_New";
    directoryCopy(SOURCE_DIR, TARGET_DIR);
  }

  private static void directoryCopy(String sourceDir, String targetDir){
    Path sourcePath = Paths.get(sourceDir);
    Path targetPath = Paths.get(targetDir);
    try(Stream<Path> filePaths = Files.walk(sourcePath)) {
      filePaths.forEach(filePath -> {
        try {
          if (Files.isRegularFile(filePath)) {
            Path newFile = targetPath.resolve(sourcePath.relativize(filePath));
            Files.copy(filePath, newFile);
            System.out.println("Copied file " + newFile);
          }else{
            Path newDir = targetPath.resolve(sourcePath.relativize(filePath));
            Files.createDirectory(newDir);
            System.out.println("Created Directory " + newDir);
          }
        }catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } 
      });
    }catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
Created Directory F:\knpcode\Parent_New
Created Directory F:\knpcode\Parent_New\Child
Copied file F:\knpcode\Parent_New\Child\hello.txt
Copied file F:\knpcode\Parent_New\Child\Project.docx
Copied file F:\knpcode\Parent_New\Test.txt

Copying directory in Java using Files.walkFileTree() method

Java 7 onward You can use Files.walkFileTree() method using which you can walk the tree structure of the source directory and copy all files and sub-directories in the process.

One of the argument of this method is a FileVisitor interface. You do need to provide implementation of this interface as per your requirement.

FileVisitor interface has four methods, for listing files in a folder you do need to implement two of them; preVisitDirectory and visitFile.

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class CopyDirectory {
  public static void main(String[] args) {
    final String SOURCE_DIR = "F:/knpcode/Parent";
    final String TARGET_DIR = "G:/Parent_New";
    try {
      directoryCopy(SOURCE_DIR, TARGET_DIR);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  private static void directoryCopy(String sourceDir, String targetDir) throws IOException{
    Path sourcePath = Paths.get(sourceDir);
    Path targetPath = Paths.get(targetDir);
    // Walk the tree structure using WalkFileTree method       
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
      @Override
      // Before visiting the directory, create directory 
      public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
        Path newDir = targetPath.resolve(sourcePath.relativize(dir));
        System.out.println("Path- " + newDir.toString());
        Files.createDirectory(newDir);
        return FileVisitResult.CONTINUE;
      }
      @Override
      // For each visited file copy it
      public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
        Path newFile = targetPath.resolve(sourcePath.relativize(file));
        System.out.println("Path- " + newFile.getFileName());
        Files.copy(file, newFile);                
        return FileVisitResult.CONTINUE;
      }
    });  
  }
}

Copying directory in Java using File.listFiles() method

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class CopyDirectory {
  public static void main(String[] args) {
    final String SOURCE_PATH = "F:/knpcode/Parent";
    final String TARGET_PATH = "F:/knpcode/Parent_New";
    File sourceDir = new File(SOURCE_PATH);
    File targetDir = new File(TARGET_PATH);
    try {
      directoryCopy(sourceDir, targetDir);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  private static void directoryCopy(File sourceDir, File targetDir) throws IOException{
    if(sourceDir.isDirectory()){
      // create target directory
      if(!targetDir.exists()){
        targetDir.mkdir();
        System.out.println("Created Directory " + targetDir);
      }
      File[] fileList = sourceDir.listFiles();
      for(File file : fileList){
        File sourceFile =  new File(sourceDir, file.getName());
        File targetFile = new File(targetDir, file.getName());
        // Recursive call in case of directory
        directoryCopy(sourceFile, targetFile);
      }
    }else{ // if it is a file
      Files.copy(sourceDir.toPath(), targetDir.toPath());
      System.out.println("Copied file " + targetDir);
    }
  }
}
Output
Created Directory F:\knpcode\Parent_New
Created Directory F:\knpcode\Parent_New\Child
Copied file F:\knpcode\Parent_New\Child\hello.txt
Copied file F:\knpcode\Parent_New\Child\Project.docx
Copied file F:\knpcode\Parent_New\Test.txt

That's all for the topic How to Copy a Directory in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment