Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Files.move()

Moves or renames a file or a folder.

Available since: Java 7

Syntax

public static Path move(Path source, Path target, CopyOption... options)

Parameters

ParameterTypeDescription
sourcePathWhat to move.
targetPathThe new path, including the name.
optionsCopyOption...Optional: REPLACE_EXISTING, ATOMIC_MOVE.

Return value

PathThe new path.

Examples

Renaming a file in the same folder:

void main() throws IOException {
    Path dir = Files.createTempDirectory("demo");
    Path draft = Files.writeString(dir.resolve("draft.txt"), "Report");
 
    Path report = Files.move(draft, dir.resolve("report.txt"));
    IO.println(report.getFileName());
    IO.println(Files.exists(draft));
}

Output:

report.txt
false

Moving into another folder, replacing an existing file:

void main() throws IOException {
    Path dir = Files.createTempDirectory("demo");
    Path archive = Files.createDirectories(dir.resolve("archive"));
    Files.writeString(archive.resolve("log.txt"), "old log");
    Path log = Files.writeString(dir.resolve("log.txt"), "new log");
 
    Files.move(log, archive.resolve("log.txt"), StandardCopyOption.REPLACE_EXISTING);
    IO.println(Files.readString(archive.resolve("log.txt")));
}

Output:

new log

Notes

Without REPLACE_EXISTING, moving onto an existing file throws FileAlreadyExistsException. The destination folder must exist. ATOMIC_MOVE guarantees that other programs see either the old or the new file, never half of it — handy for writing through a temporary file. Moving a folder to another drive may fail: then copy it and delete the original.

See also

  • Files.copy() — Copies a file. By default it does not overwrite an existing file.
  • Files.delete() — Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
  • Files.createDirectories() — Creates a folder together with all missing parent folders.
  • Path.of() — Creates a Path object — a path to a file or folder.

In the tutorial

  • Files and paths — Working with the file system in Java — Path, Files.exists, creating folders and files, size, copying, moving, deleting and listing files.

Thanks for reading!

Donate to the site — we work hard for you.