The following program copies a file using a call to a NIO method: copy()
.
It is a static method defined by Files.
static Path copy(Path src, Path dest, CopyOption ... how) throws IOException
CopyOption
can be:
StandardCopyOption.COPY_ATTRIBUTES Request that the file's attributes be copied. StandardLinkOption.NOFOLLOW_LINKS Do not follow symbolic links. StandardCopyOption.REPLACE_EXISTING Overwrite a preexisting file.
// Copy a file using NIO. import java.io.IOException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class Main { public static void main(String args[]) { try {// w ww.j av a 2 s.c o m Path source = Paths.get("Main.java"); Path target = Paths.get("Main1.java"); // Copy the file. Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } catch (InvalidPathException e) { System.out.println("Path Error " + e); } catch (IOException e) { System.out.println("I/O Error " + e); } } }