Java Move or Rename File with Files.move() Method Example

In this example, I show you how to move or rename a file in Java using Files.move() API.

java.nio.file.Files.move() API

This method is used to move or rename a file to a target file.
By default, this method attempts to move the file to the target file, failing if the target file exists except if the source and target are the same files, in which case this method has no effect.

Java Files.move() API Example


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaMoveFile {

    public static void main(String[] args) throws IOException {

        Path myPath = Paths.get("src/myfile.txt");
        Path myPath2 = Paths.get("src/myfile2.txt");

        Files.move(myPath, myPath2);

        System.out.println("File moved");
File moved

The above example renames the "src/myfile.txt" file to "src/myfile2.txt".
Files.move() method takes two parameters: the source file path and the destination file path.
Files.move(myPath, myPath2);


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course