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


Example:
package org.code2care.java.examples;

import java.io.IOException;
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(
                    sourceFile,
                    destinationDirPath.resolve(sourceFile.getFileName()),
                    StandardCopyOption.REPLACE_EXISTING
            );

            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:

/path/to/destination/directory/file.txt

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

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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