How do I copy a file in JDK 7?

In this example you’ll see how to copy a file using the new API provided in the JDK 7. The first step is to define the source and the target of the file to be copied. For this we can use the Path class. To create an instance of Path we use the Paths.get() method by passing the path information as the arguments.

Next we can configure the file copy operation option. For this we can define it as an array of CopyOtion. We can use copy option such as StandardCopyOption.REPLACE_EXISTING and StandardCopyOption.COPY_ATTRIBUTES.

Finally, to copy the file we use the Files.copy() method. We give three arguments to this method, they are the source file, the target file and the copy options information.

Let’s see the code snippet below:

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.*;

public class NioFileCopyDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be copied.
        Path source = Paths.get("D:/resources/data.txt");
        Path target = Paths.get("D:/resources/data.bak");

        // Define the options used in the file copy process.
        CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES
        };

        try {
            // Copy file from source to target using the defined 
            // configuration.
            Files.copy(source, target, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Wayan

Leave a Reply

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