Move a File in Java

In this quick tutorial, we will learn different ways to move a file in Java.

1. Move File using File.renameTo() Method

  1. Create a file named "sample.txt" in the directory "C:/workspace".
  2. Create File class object by passing file absolute location path "C:/workspace/sample.txt".
  3. We need to pass the new abstract pathname to renameTo() method to move the file.
  4. renameTo() method returns true if and only if the renaming succeeded; false otherwise.
  5. Observe the directory whether the file is moved or not.
import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This Java program demonstrates how to move file in Java.
 * @author javaguides.net
 */

public class MoveFileExample {

    private static final Logger LOGGER = LoggerFactory.getLogger(MoveFileExample.class);

    public static void main(String[] args) {
        moveFile();
    }

    public static void moveFile() {
        File file = new File("C:/workspace/sample.txt");
        boolean move = file.renameTo(new File("C:/workspace/moved/sample.txt"));
        if (move) {
            LOGGER.info("File is moved successful!");
        } else {
            LOGGER.info("File is failed to move!");
        }
    }
}

2. Move File using Files.move() Method

java.nio.file.Files provide several static methods that operate on files, directories, or other types of files. To move a file to a target file, we can use its move() method:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
 
public class Main
{
    public static void main(String[] args)
    {
        File from = new File("src.txt");
        File to = new File("dest.txt");
 
        try {
            Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File moved successfully.");
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Comments