Files.copy
A file exists at one location, but we want to copy it to another location. This is a task for Files.copy
, a useful method from Java.nio.file
.
With this method, we do not need to process the file contents. We do not need to read in the file—this also has speed and memory benefits.
Here we get two Path
objects from the default FileSystem
. We then pass these Path
objects to Files.copy
, which has two arguments.
Files.copy
is the location of the currently-existing file we want to copy.CopyOption
, specifies overwrite behavior.import java.io.IOException; import java.nio.file.*; public class Program { public static void main(String[] args) throws IOException { // Get paths for input and target files. FileSystem system = FileSystems.getDefault(); Path original = system.getPath("C:\\programs\\file.txt"); Path target = system.getPath("C:\\programs\\file-2.txt"); // Copy original to target location. Files.copy(original, target); // Helpful message. System.out.println("File copied!"); } }File copied!
Replace
existing fileHere we use a CopyOption
as the third argument to Files.copy
. CopyOption
is an interface
—we specify it as a StandardCopyOption
.
Replace
existing means the existing target file is silently replaced. No exception occurs.IOException
may still occur. One possible problem is the original file might not exist.import java.io.IOException; import java.nio.file.*; public class Program { public static void main(String[] args) throws IOException { // Get paths. Path original = FileSystems.getDefault().getPath( "C:\\programs\\file.txt"); Path target = FileSystems.getDefault().getPath( "C:\\programs\\file-2.txt"); // Replace an existing file with REPLACE_EXISTING. // ... No FileAlreadyExistsException will be thrown. Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING); System.out.println("DONE"); } }DONE
The Files.copy
method can throw exceptions in many circumstances. If the original file is missing, it will cause an IOException
.
try-catch
block. We can report an error message on failure.import java.io.IOException; import java.nio.file.*; public class Program { public static void main(String[] args) { // These files do not exist in our example. FileSystem system = FileSystems.getDefault(); Path original = system.getPath("C:\\programs\\mystery.txt"); Path target = system.getPath("C:\\programs\\mystery-2.txt"); try { // Throws an exception if the original file is not found. Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { System.out.println("ERROR"); } } }ERROR
Programs commonly need to copy files. With Files.copy
from java.nio.file
, we copy a file at one path to another. Some of the syntax is confusing.
And with file interactions, errors may always occur. These might not be the fault of your program logic. A file might be missing for external reasons.