1. import java.io.File;
  2. import java.io.IOException;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6. import java.time.LocalDateTime;
  7. import java.time.format.DateTimeFormatter;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. public class FileBackup {
  11. private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
  12. private static final String BACKUP_DIR = "backups"; // Directory to store backups
  13. public static void main(String[] args) {
  14. if (args.length != 2) {
  15. System.err.println("Usage: java FileBackup <source_directory> <destination_directory>");
  16. System.exit(1);
  17. }
  18. String sourceDir = args[0];
  19. String destDir = args[1];
  20. File source = new File(sourceDir);
  21. File dest = new File(destDir);
  22. if (!source.exists()) {
  23. System.err.println("Source directory does not exist: " + sourceDir);
  24. System.exit(1);
  25. }
  26. if (!dest.exists()) {
  27. if (!dest.mkdirs()) {
  28. System.err.println("Failed to create destination directory: " + destDir);
  29. System.exit(1);
  30. }
  31. }
  32. backupDirectory(source, dest);
  33. }
  34. public static void backupDirectory(File source, File dest) {
  35. String timestamp = LocalDateTime.now().format(formatter);
  36. String backupFileName = "backup_" + timestamp;
  37. File backupDir = new File(dest, backupFileName);
  38. try {
  39. if (!backupDir.mkdirs()) {
  40. System.err.println("Failed to create backup directory: " + backupDir);
  41. return;
  42. }
  43. backupDirectoryHelper(source, backupDir);
  44. System.out.println("Backup completed successfully to: " + backupDir.getAbsolutePath());
  45. } catch (IOException e) {
  46. System.err.println("Error during backup: " + e.getMessage());
  47. }
  48. }
  49. private static void backupDirectoryHelper(File source, File dest) throws IOException {
  50. List<String> files = new ArrayList<>();
  51. for (File file : source.listFiles()) {
  52. String filePath = file.getAbsolutePath();
  53. String relativePath = file.getAbsolutePath().replace(source.getAbsolutePath(), "");
  54. files.add(relativePath);
  55. }
  56. for (String relativePath : files) {
  57. Path sourcePath = Paths.get(source.getAbsolutePath() + "/" + relativePath);
  58. Path destPath = Paths.get(dest.getAbsolutePath() + "/" + relativePath);
  59. Files.copy(sourcePath, destPath);
  60. System.out.println("Copied: " + sourcePath + " to " + destPath);
  61. }
  62. }
  63. }

Add your comment