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;
import java.util.ArrayList;
import java.util.List;
public class FileBackup {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
private static final String BACKUP_DIR = "backups"; // Directory to store backups
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java FileBackup <source_directory> <destination_directory>");
System.exit(1);
}
String sourceDir = args[0];
String destDir = args[1];
File source = new File(sourceDir);
File dest = new File(destDir);
if (!source.exists()) {
System.err.println("Source directory does not exist: " + sourceDir);
System.exit(1);
}
if (!dest.exists()) {
if (!dest.mkdirs()) {
System.err.println("Failed to create destination directory: " + destDir);
System.exit(1);
}
}
backupDirectory(source, dest);
}
public static void backupDirectory(File source, File dest) {
String timestamp = LocalDateTime.now().format(formatter);
String backupFileName = "backup_" + timestamp;
File backupDir = new File(dest, backupFileName);
try {
if (!backupDir.mkdirs()) {
System.err.println("Failed to create backup directory: " + backupDir);
return;
}
backupDirectoryHelper(source, backupDir);
System.out.println("Backup completed successfully to: " + backupDir.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error during backup: " + e.getMessage());
}
}
private static void backupDirectoryHelper(File source, File dest) throws IOException {
List<String> files = new ArrayList<>();
for (File file : source.listFiles()) {
String filePath = file.getAbsolutePath();
String relativePath = file.getAbsolutePath().replace(source.getAbsolutePath(), "");
files.add(relativePath);
}
for (String relativePath : files) {
Path sourcePath = Paths.get(source.getAbsolutePath() + "/" + relativePath);
Path destPath = Paths.get(dest.getAbsolutePath() + "/" + relativePath);
Files.copy(sourcePath, destPath);
System.out.println("Copied: " + sourcePath + " to " + destPath);
}
}
}
Add your comment