Copy File Example.

Java NIO - Copy File Example

  • Java
  • 2 mins read

Use the copy() method to copy a file from one directory to another in Java using NIO. In this tutorial, I am giving an example of a Java program to copy a file using NIO I/O system.

There are several forms of the NIO copy() method. Below is the syntax form; I am using for this demonstration:

static Path copy(Path src, Path dest, CopyOption.method)

The file specified for the source (src) will be copied to the file specified for the destination (dest). How the copy is performed is specified by the CopyOption.method. The following are the valid values for this parameter:

copy() Method CopyOptionDescription
StandardCopyOption.COPY_ATTRIBUTESRequest that the file's attributes be copied.
StandardLinkOption.NOFOLLOW_LIINKSDo not follow symbolic links.
StandardCopyOption.REPLACE_EXISTINGOverwrite a preexisting file.

Java NIO - Copy File Example Using the copy() Method

The following Java program accepts two arguments, the source file, and the target file to copy a file using Java NIO. The file will be replaced with a new file if already exists because it is using REPLACE_EXISTING option.

// NIOFileCopy.java
// Copy a file using Java NIO
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.file.*;
public class NIOFileCopy {
    public static void main (String args[]) {
        if (args.length != 2) {
            System.out.println("Parameters: source file, target file");
            return;
        }
        
        try {
            Path source = Paths.get(args[0]);
            Path target = Paths.get(args[1]);
            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
            
        } catch(InvalidPathException e) {
            System.out.println("Path Error " + e);
        } catch(IOException e) {
                System.out.println("Path Error " + e);
        }
            
    }
}

Run Test

java NIOFileCopy F:\files\temp.txt F:\files\temp\temp2.txt

See also: