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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!