CodeGym /Courses /JAVA 25 SELF /Copying and moving files and folders

Copying and moving files and folders

JAVA 25 SELF
Level 40, Lesson 1
Available

1. Copying files

Method Files.copy: basic syntax

In Java, the static method Files.copy from the java.nio.file package is used to copy files and folders. We’ve already encountered it, but now we’ll look at it in more detail. The basic syntax of Files.copy:

Files.copy(Path source, Path target, CopyOption... options)
  • source — path to the source file or folder.
  • target — path to copy to.
  • options — additional options (for example, allow overwrite).

The simplest example

Let’s copy the file "input.txt" from the current directory to the "backup" folder with the name "input_backup.txt":

import java.nio.file.*;

public class CopyExample {
    public static void main(String[] args) throws Exception {
        Path source = Path.of("input.txt");
        Path target = Path.of("backup/input_backup.txt");

        Files.copy(source, target);
        System.out.println("File copied!");
    }
}

Important points:

  • If the target file already exists, a FileAlreadyExistsException will be thrown.
  • If the "backup" folder does not exist, the method will throw an error — the folder must be created beforehand!

Copying with overwrite

To allow overwriting the file, use the StandardCopyOption.REPLACE_EXISTING option:

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

Table: key copy options

Option Description
StandardCopyOption.REPLACE_EXISTING
Overwrite the file if it already exists
StandardCopyOption.COPY_ATTRIBUTES
Copy attributes (creation time, etc.)
StandardCopyOption.ATOMIC_MOVE
Atomic move (used only with move)

Copying a file into another folder

Before copying a file, make sure the destination folder exists:

Path targetDir = Path.of("backup");
if (!Files.exists(targetDir)) {
    Files.createDirectory(targetDir);
}
Files.copy(source, targetDir.resolve("input_backup.txt"), StandardCopyOption.REPLACE_EXISTING);

Copying directories: a gotcha

The Files.copy method can copy folders only as an “empty shell” — the contents (files and subfolders) are not copied! If you try to copy a folder with files, you’ll get only an empty directory. To copy entire directories with their contents, you need a recursive walk and manual copying of each file (we’ll get back to this in later lectures).

Example: copy a file from one folder to another

Path source = Path.of("data/report.txt");
Path target = Path.of("backup/report.txt");

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

Error handling when copying

Copying can fail for various reasons: no access, the file is in use, not enough space, the file already exists, etc. It’s better to always use try-catch:

try {
    Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
    System.out.println("Copy successful!");
} catch (FileAlreadyExistsException e) {
    System.out.println("File already exists: " + target);
} catch (IOException e) {
    System.out.println("I/O error: " + e.getMessage());
}

2. Moving files and folders

Method Files.move: syntax

Moving files and folders is performed with the method:

Files.move(Path source, Path target, CopyOption... options)

Where source is the path to the file (where we move from), target is where we want to put the file or folder, and options are additional settings (for example, replacing an existing file).

By the way, moving is not only a file “relocation”, but also a way to rename (if only the name changes). And if a file with the same name already exists in the target folder, an exception will be thrown unless you specify the REPLACE_EXISTING option.

Example: moving a file to another folder

Path source = Path.of("data/report.txt");
Path target = Path.of("archive/report.txt");

Files.move(source, target);
System.out.println("File moved!");

Moving with overwrite

Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

Moving a folder

Path oldDir = Path.of("data/old_reports");
Path newDir = Path.of("archive/old_reports");

Files.move(oldDir, newDir);

The entire folder, including nested files and subfolders, will move to the new location.
But if the target folder already has a folder with the same name, you’ll get an error.

Moving between different file systems

If you move a file between different drives (for example, from "C:" to "D:"), under the hood a copy will happen followed by deletion of the source file. If the operation is not supported as atomic, an AtomicMoveNotSupportedException may be thrown.

Difference between move and copy

  • copy — the source file/folder stays in place; a copy appears.
  • move — the source file/folder disappears; only the new instance remains.

3. Renaming files and folders

Java does not have a separate “rename file” method. Renaming is a special case of moving: you specify a new path with a different name in the same directory.

Example: renaming a file

Suppose we have the file "report.txt", and we want to rename it to "report_old.txt" in the same folder:

Path dir = Path.of("data");
Path oldName = dir.resolve("report.txt");
Path newName = dir.resolve("report_old.txt");

Files.move(oldName, newName);
System.out.println("File renamed!");

Important nuances

If a file or folder with the name you specify already exists in the target directory, the method will throw an exception. To bypass this limitation and allow replacement, you can use the StandardCopyOption.REPLACE_EXISTING option.

Example:

Path source = Paths.get("old_name.txt");
Path target = Paths.get("new_name.txt");

// Rename the file; if it already exists — replace it
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);

In this example, the file "old_name.txt" will be renamed to "new_name.txt". If a file with that name was already in the folder, it will be overwritten.

Renaming a folder

Path oldDir = Path.of("data/old_reports");
Path newDir = Path.of("data/archived_reports");

Files.move(oldDir, newDir);
System.out.println("Folder renamed!");

4. Error handling when copying, moving, and renaming

Working with the file system always carries the risk of unexpected situations. Here are the most common problems:

The file already exists.
Exception: FileAlreadyExistsException. Solution: use REPLACE_EXISTING if you want to overwrite.

The file or folder is in use by another process.
Exception: IOException. For example, the file is open in another program.

No access to the file or folder.
Exception: AccessDeniedException. A permissions issue.

Moving between different file systems.
Exception: AtomicMoveNotSupportedException. Not all file systems support atomic moves.

The target folder does not exist.
For copying/moving, make sure the destination folder is created in advance!

Example of error handling

try {
    Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (FileAlreadyExistsException e) {
    System.out.println("Destination file already exists: " + target);
} catch (AtomicMoveNotSupportedException e) {
    System.out.println("Atomic move is not supported: " + e.getMessage());
} catch (IOException e) {
    System.out.println("Error while moving: " + e.getMessage());
}

5. Practical recommendations

Checking if the target file/folder exists

Before copying or moving, it’s always useful to check whether the destination path is taken:

if (Files.exists(target)) {
    System.out.println("The file already exists; we won't overwrite it.");
} else {
    Files.copy(source, target);
}

Using temporary files for safe operations

For complex operations (for example, updating important files), temporary files are often used — first copy to a temporary file, and then replace the main one:

Path temp = Path.of("data/report.tmp");
Files.copy(source, temp, StandardCopyOption.REPLACE_EXISTING);
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);

This approach minimizes the risk of data loss in case of failures.

Example: backing up a file before replacing

Path file = Path.of("data/report.txt");
Path backup = Path.of("data/report_backup.txt");

if (Files.exists(file)) {
    Files.copy(file, backup, StandardCopyOption.REPLACE_EXISTING);
    System.out.println("Backup created.");
}

6. Table: key methods and options

Operation Java NIO method Notes
Copying
Files.copy(source, target, ...)
Does not copy folder contents!
Moving
Files.move(source, target, ...)
Can be used for renaming
Renaming
Files.move(source, target, ...)
New path in the same directory
Overwrite
StandardCopyOption.REPLACE_EXISTING
Overwrites the target file/folder
Check
Files.exists(path)
Checks whether a file/folder exists

7. Typical mistakes when copying, moving, and renaming files

Error #1: attempting to copy a file into a non-existent folder. If the target directory is not created, you’ll get a NoSuchFileException. Solution: create the folder in advance using Files.createDirectories.

Error #2: trying to copy a folder as a whole using Files.copy. The method will copy only an “empty shell”, not the contents. For a full copy you need a recursive walk.

Error #3: not handling an existing file. If you don’t pass REPLACE_EXISTING and the file already exists, an exception will be thrown. It’s better to handle this case explicitly.

Error #4: trying to rename a file when a file with the new name already exists. Similarly, you’ll get a FileAlreadyExistsException. Before renaming, you can check for the file’s existence.

Error #5: moving between different file systems. Sometimes the operation is not supported “atomically” and AtomicMoveNotSupportedException is thrown. In this case, use a regular non-atomic move.

Error #6: insufficient permissions or the file is locked. If the file is open in another program or you don’t have write/read permissions, you’ll get AccessDeniedException or IOException. Always handle such exceptions.

1
Task
JAVA 25 SELF, level 40, lesson 1
Locked
Moving the fresh report to the archive 📦
Moving the fresh report to the archive 📦
1
Task
JAVA 25 SELF, level 40, lesson 1
Locked
Renaming an Outdated Document 📝
Renaming an Outdated Document 📝
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION