import java.io.File; import org.apache.commons.io.FileUtils; public class FileCopyExample { public static void main(String[] args) { File source = new File("source.txt"); File destination = new File("destination.txt"); try { FileUtils.copyFile(source, destination); System.out.println("File copied successfully"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }
import java.io.File; import org.apache.commons.io.FileUtils; public class DirectoryCopyExample { public static void main(String[] args) { File source = new File("sourceDir"); File destination = new File("destinationDir"); try { FileUtils.copyDirectory(source, destination); System.out.println("Directory copied successfully"); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } }In both examples, we are using the copyFile and copyDirectory methods of the FileUtils class to perform the file and directory copy operation, respectively. We also handle any exceptions that may occur during the copy operation. The org.apache.commons.io package library is required to use these examples, which can be downloaded from the Apache Commons IO website.