Copying Files and Directories - Java File Path IO

Java examples for File Path IO:File Copy

Introduction

Copying options are listed here:

  • REPLACE_EXISTING: If the copied file already exists, then it is replaced. For a symbolic link, the target is not copied, only the link is copied.
  • COPY_ATTRIBUTES: Copy a file with its associated attributes (at least, the lastModifiedTime attribute is supported and copied).
  • NOFOLLOW_LINKS: Symbolic links should not be followed.

To copy only the symbolic link itself, use the REPLACE_EXISTING and NOFOLLOW_LINKS options.

Copying Between Two Paths

Demo Code


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {
  public static void main(String[] args) throws Exception {

    Path copy_from = Paths.get("C:/folder1/folder0/folder9",
        "draw_template.txt");
    Path copy_to = Paths.get("C:/folder1/folder0/USOpen", copy_from
        .getFileName().toString());/*from w  ww  . j av  a  2 s.c  o m*/

    try {

      Files.copy(copy_from, copy_to, StandardCopyOption.REPLACE_EXISTING,
          StandardCopyOption.COPY_ATTRIBUTES, LinkOption.NOFOLLOW_LINKS);

    } catch (IOException e) {
      System.err.println(e);
    }
  }
}

Result


Related Tutorials