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.




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

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

        // A temporary folder where we are gonna copy the source file to.
        // Here we use the temporary folder of the OS, which can be
        // obtained using property.
        File targetDir = new File(System.getProperty(""));

        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 folder 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

Maven Dependencies


Maven Central