How to Delete, Copy and Move Files in Java

Naveen AnamaneniUpdated · 3 min read
easyJava 25javafilesnio

Besides reading and writing, programs often need to manage files: delete old ones, copy them for backups, and move or rename them. NIO.2 does each with one call: Files.delete, Files.deleteIfExists, Files.copy and Files.move. By default, copy and move refuse to overwrite an existing target; copy options change this. In this lesson, you will learn these methods and their options.

Methods

MethodDescription
Files.delete(path)It is used to delete a file or empty folder; throws NoSuchFileException if missing.
Files.deleteIfExists(path)It deletes if present and returns true, otherwise returns false.
Files.copy(source, target, options...)It copies a file.
Files.move(source, target, options...)It moves or renames a file.

Copy and Move Options

OptionEffect
StandardCopyOption.REPLACE_EXISTINGOverwrite the target if it exists
StandardCopyOption.COPY_ATTRIBUTESKeep timestamps and other attributes when copying
StandardCopyOption.ATOMIC_MOVEMove in one step, so no one sees a half-moved file

Example: Copy, Rename and Delete

Let's see an example that manages a report file.

Manage.java▶ Try it
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
 
public class Manage {
    public static void main(String[] args) throws IOException {
        Path report = Path.of("report.txt");
        Files.writeString(report, "Navika: 91");
 
        Path copy = Files.copy(report, Path.of("report-copy.txt"));
        System.out.println("Copied to " + copy);
 
        try {
            Files.copy(report, copy);
        } catch (FileAlreadyExistsException e) {
            System.out.println("Refused to overwrite " + e.getMessage());
        }
        Files.writeString(report, "Navika: 95");
        Files.copy(report, copy, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Copy now says: " + Files.readString(copy));
 
        Path renamed = Files.move(copy, Path.of("final-report.txt"));
        System.out.println("Renamed to " + renamed
            + "; old name exists? " + Files.exists(copy));
 
        Files.delete(renamed);
        System.out.println("deleteIfExists again: "
            + Files.deleteIfExists(renamed));
    }
}
Output
Copied to report-copy.txt
Refused to overwrite report-copy.txt
Copy now says: Navika: 95
Renamed to final-report.txt; old name exists? false
deleteIfExists again: false

Explanation: The first copy works. Copying again fails, because copies never overwrite by default; REPLACE_EXISTING allows it. Files.move within the same folder is a rename. After delete, deleteIfExists simply returns false instead of throwing.

Deleting Folders

Files.delete deletes a folder only if it's empty; otherwise it throws DirectoryNotEmptyException. To delete a folder tree, walk it and delete the deepest entries first, as shown in "Working with Directories in Java".

Common Mistakes

Expecting copy to overwrite. Pass REPLACE_EXISTING.

Deleting a non-empty folder with Files.delete. Delete its contents first.

Moving into a folder by passing only the folder as target. The target must be the full new path: dir.resolve(file.getFileName()).

Practice

  1. Easy: Copy notes.txt into a backup folder, keeping the same file name.
  2. Harder: Rename every .txt file in a folder to .bak using Files.list and Files.move.

Quick check: Delete, copy, move

4 questions
1What does Files.copy do if the target exists?
2How do you rename a file?
3What does deleteIfExists return for a missing file?
4Can Files.delete remove a non-empty folder?

Key Takeaways

Was this tutorial helpful?

Lesson 359 of 482