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. public class FileBackup {
  9. public static void backupFiles(String sourceDir, String backupDir) {
  10. // Create the backup directory if it doesn't exist
  11. File backupDirectory = new File(backupDir);
  12. if (!backupDirectory.exists()) {
  13. backupDirectory.mkdirs(); //Create parent directories if needed
  14. }
  15. // Get the current date and time for the backup file name
  16. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
  17. String timestamp = LocalDateTime.now().format(formatter);
  18. String backupFileName = "backup_" + timestamp;
  19. Path backupPath = Paths.get(backupDir + "/" + backupFileName);
  20. try {
  21. // Copy all files from the source directory to the backup directory
  22. File sourceFile = new File(sourceDir);
  23. if (sourceFile.isDirectory()) {
  24. Files.copy(sourceFile.toPath(), backupPath);
  25. System.out.println("Backup created successfully at: " + backupPath);
  26. } else if (sourceFile.isFile()) {
  27. Files.copy(sourceFile.toPath(), backupPath);
  28. System.out.println("Backup created successfully at: " + backupPath);
  29. }
  30. else {
  31. System.out.println("Source directory does not exist or is not a file/directory.");
  32. }
  33. } catch (IOException e) {
  34. System.err.println("Error during backup: " + e.getMessage());
  35. }
  36. }
  37. public static void main(String[] args) {
  38. // Example usage:
  39. String sourceDirectory = "/path/to/your/source/directory"; // Replace with your source directory
  40. String backupDirectory = "/path/to/your/backup/directory"; // Replace with your backup directory
  41. backupFiles(sourceDirectory, backupDirectory);
  42. }
  43. }

Add your comment