Java - File Input Output Copy Files

Introduction

Files class copy(Path source, Path target, CopyOption... options) method can copy contents and attributes of a file.

If the specified source file is a symbolic link, the target of the symbolic link is copied, not the symbolic link.

If the specified source file is a directory, an empty directory at the target location is created without copying the contents of the directory.

This method is overloaded. You can use the other two versions to copy all bytes from an input stream to a file and all bytes in a file to an output stream.

If the specified source and target files are the same, the copy() method does not do anything.

You can specify one or more of the following copy options with the copy() method:

StandardCopyOption.REPLACE_EXISTING
StandardCopyOption.COPY_ATTRIBUTES
LinkOption.NOFOLLOW_LINKS

If the target file already exists, the copy() method throws a FileAlreadyExistsException.

You can specify the REPLACE_EXISTING option to replace the existing target file.

If the target file is a non-empty directory, specifying the REPLACE_EXISTING option throws a DirectoryNotEmptyException.

If the target file is a symbolic link and if it exists, the symbolic link is replaced by specifying the REPLACE_EXISTING option, not the target of the symbolic link.

The COPY_ATTRIBUTES option copies the attributes of the source file to the target file.

The last-modified-time attribute of the source file is copied to the target file, if supported.

If the NOFOLLOW_LINKS option is used, the copy() method copies the symbolic link, not the target of the symbolic link.

The following code uses the copy() method to copy a file.

It handles the possible exceptions if the copy operation fails.

Demo

import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    // Change the paths for the source and target files
    // before you run the program
    Path source = Paths.get("C:\\myData\\Main.java");
    Path target = Paths.get("C:\\myData\\test1_backup.txt");

    try {//from   w ww. j ava2  s.  c  o m
      Path p = Files.copy(source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);
      System.out.println(source + " has been copied to " + p);
    } catch (FileAlreadyExistsException e) {
      System.out.println(target + " already exists.");
    } catch (DirectoryNotEmptyException e) {
      System.out.println(target + " is not empty.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result