How do I create a copy of a file?

This example shows how we can use the Apache Commons IO library to simplify a file copy process.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

public class FileCopyExample {
    public static void main(String[] args) {
        // The source file name to be copied.
        File source = new File("README.md");

        // The target file name to which the source file will be copied.
        File target = new File("README-BACKUP.md");

        // A temporary directory where we are going to copy the source file to.
        // Here we use the temporary directory of the operating system, which 
        // can be obtained using java.io.tmpdir property.
        File targetDir = new File(System.getProperty("java.io.tmpdir"));

        try {
            // Using FileUtils.copyFile() method to copy a file.
            System.out.println("Copying " + source + " file to " + target);
            FileUtils.copyFile(source, target);

            // To copy a file to a specified directory, we can use the
            // FileUtils.copyFileToDirectory() method.
            System.out.println("Copying " + source + " file to " + targetDir);
            FileUtils.copyFileToDirectory(source, targetDir);
        } catch (IOException e) {
            // Errors will be reported here if any error occurs during 
            // copying the file
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.