C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: The first argument to Files.copy is the location of the currently-existing file we want to copy.
Argument 2: The target location we want to create. A third argument, a CopyOption, specifies overwrite behavior.
Result: If the file.txt exists, it is copied to the new location file-2.txt. Both files exist after running the program.
Java program that copies a file
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!");
}
}
Output
File copied!
Exception text: Java
Exception in thread "main" java.nio.file.FileAlreadyExistsException:
C:\programs\file-2.txt
at sun.nio.fs.WindowsFileCopy.copy(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.copy(Unknown Source)
at java.nio.file.Files.copy(Unknown Source)
at program.Program.main(Program.java:15)
REPLACE_EXISTING: This means the existing target file is silently replaced. No exception occurs.
Caution: An IOException may still occur. One possible problem is the original file might not exist.
Java program that copies, replaces existing file
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");
}
}
Output
DONE
Thus: An ideal way to deal with the errors here is to employ a try-catch block. We can report an error message on failure.
ExceptionsJava program that uses Files.copy, try and catch
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");
}
}
}
Output
ERROR