How to Copy a File or Directory In Java?

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

You can copy a file or directory in Java using copy() method:

                                public static Path copy(Path source,
                                                        Path target,
                                                        CopyOption... options)
                                                 throws IOException

This method copies a file to the target file with the options parameter specifying how the copy is performed. According to Java documentation options parameter may include any of the following:

If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file stores. Copying of file timestamps may result in precision loss.
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link.

Here is a simple Java program that shows how to copy a file:


                            import java.nio.file.Files;
                            import java.nio.file.Path;
                            import java.nio.file.Paths;

                            public class JavaCopyFileExample {

                                public static void main(String[] args) throws IOException {
                                    Path source = Paths.get("/home/manish/sample.txt");
                                    Path destination = Paths.get("/home/manish/Desktop/sample.txt");
                                    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                                    System.out.println("File copied!");