import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class FileCopier { public static void copyFileWithReplace(String sourceFilePath, String destinationDirectoryPath) { try { Path sourcePath = Paths.get(sourceFilePath); Path destinationDir = Paths.get(destinationDirectoryPath); // Create the destination directory if it doesn't exist if (!Files.exists(destinationDir)) { Files.createDirectories(destinationDir); } // Construct the target file path in the destination directory Path targetPath = destinationDir.resolve(sourcePath.getFileName()); // Copy the file with REPLACE_EXISTING option Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); System.out.println("File copied successfully from " + sourceFilePath + " to " + targetPath.toString()); } catch (IOException e) { System.err.println("Error copying file: " + e.getMessage()); } } public static void main(String[] args) { // Example usage: String sourceFile = "C:/temp/source/myFile.txt"; // Replace with your source file path String destinationDirectory = "C:/temp/destination"; // Replace with your destination directory path copyFileWithReplace(sourceFile, destinationDirectory); } }