Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a folder and all its subfolders and files into another folder [duplicate]

Tags:

java

How can I copy a folder and all its subfolders and files into another folder?

like image 797
user496949 Avatar asked Mar 20 '11 13:03

user496949


People also ask

How do I copy a folder and subfolders?

Type "xcopy", "source", "destination" /t /e in the Command Prompt window. Instead of “ source ,” type the path of the folder hierarchy you want to copy. Instead of “ destination ,” enter the path where you want to store the copied folder structure. Press “Enter” on your keyboard.

How do I copy everything from one folder to another?

Select the file you want to copy by clicking on it once. Right-click and pick Copy, or press Ctrl + C . Navigate to another folder, where you want to put the copy of the file. Click the menu button and pick Paste to finish copying the file, or press Ctrl + V .

How do I duplicate folders?

Open your folder, and select all the files ( Control + a or Command + a). Right-click and select Make a copy. That will create a new copy of each of those files, right in the same folder, with Copy of before their original file name.

Can you duplicate a folder in Windows?

Alternatively, right-click the folder, select Show more options and then Copy. In Windows 10 and earlier versions, right-click the folder and select Copy, or click Edit and then Copy. Navigate to the location where you want to place the folder and all its contents.


1 Answers

Choose what you like:

  • FileUtils from Apache Commons IO (the easiest and safest way)

Example with FileUtils:

File srcDir = new File("C:/Demo/source");
File destDir = new File("C:/Demo/target");
FileUtils.copyDirectory(srcDir, destDir);
  • Manually, example before Java 7 (CHANGE: close streams in the finally-block)
  • Manually, Java >=7

Example with AutoCloseable feature in Java 7:

public void copy(File sourceLocation, File targetLocation) throws IOException {
    if (sourceLocation.isDirectory()) {
        copyDirectory(sourceLocation, targetLocation);
    } else {
        copyFile(sourceLocation, targetLocation);
    }
}

private void copyDirectory(File source, File target) throws IOException {
    if (!target.exists()) {
        target.mkdir();
    }

    for (String f : source.list()) {
        copy(new File(source, f), new File(target, f));
    }
}

private void copyFile(File source, File target) throws IOException {        
    try (
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target)
    ) {
        byte[] buf = new byte[1024];
        int length;
        while ((length = in.read(buf)) > 0) {
            out.write(buf, 0, length);
        }
    }
}
like image 193
lukastymo Avatar answered Oct 05 '22 22:10

lukastymo