Java 8: Move a file from Source to Target Directory Example


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

public class Java8FileMover {

    private static final String SRC_FILE_LOCATION = "/path/to/source/";
    private static final String DEST_FILE_LOCATION = "/path/to/destination/directory/";
    private static final String FILE_NAME = "file.txt";

    public static void main(String[] args) {

        Path sourceFile = Path.of(SRC_FILE_LOCATION + FILE_NAME);
        Path destinationDirPath = Path.of(DEST_FILE_LOCATION);

        try {
            Path targetFile = Files.move(

            System.out.println("File moved to location: " + targetFile);
        } catch (IOException ioException) {
            System.err.println("Error occurred while moving the file: " + ioException.getMessage());

Output: File moved to location:



Facing issues? Have Questions? Post them here! I am happy to answer!

Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap