import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FileBackup {
public static void backupFiles(String sourceDir, String backupDir) {
// Create the backup directory if it doesn't exist
File backupDirectory = new File(backupDir);
if (!backupDirectory.exists()) {
backupDirectory.mkdirs(); //Create parent directories if needed
}
// Get the current date and time for the backup file name
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
String timestamp = LocalDateTime.now().format(formatter);
String backupFileName = "backup_" + timestamp;
Path backupPath = Paths.get(backupDir + "/" + backupFileName);
try {
// Copy all files from the source directory to the backup directory
File sourceFile = new File(sourceDir);
if (sourceFile.isDirectory()) {
Files.copy(sourceFile.toPath(), backupPath);
System.out.println("Backup created successfully at: " + backupPath);
} else if (sourceFile.isFile()) {
Files.copy(sourceFile.toPath(), backupPath);
System.out.println("Backup created successfully at: " + backupPath);
}
else {
System.out.println("Source directory does not exist or is not a file/directory.");
}
} catch (IOException e) {
System.err.println("Error during backup: " + e.getMessage());
}
}
public static void main(String[] args) {
// Example usage:
String sourceDirectory = "/path/to/your/source/directory"; // Replace with your source directory
String backupDirectory = "/path/to/your/backup/directory"; // Replace with your backup directory
backupFiles(sourceDirectory, backupDirectory);
}
}
Add your comment