TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Files.Copy: Copy File

Use the Files.copy method from Java.nio.file. Handle nonexistent files and possible exceptions.
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.
Example program. Here we get two Path objects from the default FileSystem. We then pass these Path objects to Files.copy, which has two arguments.

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!
File already exists. If the target file in a Files.copy operation exists, we will receive an exception. This can be solved (as shown next) with a CopyOption argument.
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 file. Here we use a CopyOption as the third argument to Files.copy. CopyOption is an interface—we specify it as a StandardCopyOption.

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
Handle exceptions. The Files.copy method can throw exceptions in many circumstances. If the original file is missing, it will cause an IOException.

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.

Exceptions
Java 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
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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf