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.example.nio;

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

public class FileCopyDemo {
    public static void main(String[] args) {
        //
        // Define the source and target of the file to be copied.
        //
        Path source = Paths.get("C:\resources\data.txt");
        Path target = Paths.get("C:\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 Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply