0
0
JavaHow-ToBeginner · 3 min read

How to Copy File in Java: Simple Syntax and Example

To copy a file in Java, use the Files.copy method from java.nio.file.Files class. Provide the source and target file paths as Path objects, and optionally specify copy options like StandardCopyOption.REPLACE_EXISTING to overwrite existing files.
📐

Syntax

The basic syntax to copy a file in Java uses the Files.copy method:

  • Path source: the path of the file to copy.
  • Path target: the path where the file will be copied.
  • CopyOption... options: optional flags like StandardCopyOption.REPLACE_EXISTING to overwrite the target file if it exists.
java
Files.copy(Path source, Path target, CopyOption... options) throws IOException
💻

Example

This example copies a file named source.txt to target.txt in the same directory, replacing the target if it exists.

java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.io.IOException;

public class FileCopyExample {
    public static void main(String[] args) {
        Path source = Paths.get("source.txt");
        Path target = Paths.get("target.txt");
        try {
            Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            System.out.println("Error copying file: " + e.getMessage());
        }
    }
}
Output
File copied successfully.
⚠️

Common Pitfalls

Common mistakes when copying files in Java include:

  • Not handling IOException which is required because file operations can fail.
  • Forgetting to use StandardCopyOption.REPLACE_EXISTING if you want to overwrite an existing file, which causes an exception.
  • Using incorrect file paths or missing files causing NoSuchFileException.
java
import java.nio.file.*;
import java.io.IOException;

public class WrongCopy {
    public static void main(String[] args) {
        Path source = Paths.get("missing.txt");
        Path target = Paths.get("copy.txt");
        try {
            // This will throw exception if target exists
            Files.copy(source, target);
        } catch (IOException e) {
            System.out.println("Copy failed: " + e.getMessage());
        }
    }
}

// Correct way with overwrite option:
// Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Output
Copy failed: missing.txt (No such file or directory)
📊

Quick Reference

Tips for copying files in Java:

  • Use Paths.get("filename") to create file paths.
  • Always handle IOException with try-catch.
  • Use StandardCopyOption.REPLACE_EXISTING to overwrite files.
  • Check if source file exists before copying to avoid exceptions.

Key Takeaways

Use Files.copy with Path objects to copy files in Java.
Handle IOException to manage file operation errors.
Use StandardCopyOption.REPLACE_EXISTING to overwrite existing files.
Verify source file existence to prevent runtime exceptions.
Paths.get creates file paths easily and clearly.