1. import java.io.BufferedReader;
  2. import java.io.BufferedWriter;
  3. import java.io.FileReader;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.time.LocalDateTime;
  7. import java.time.format.DateTimeFormatter;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.Scanner;
  11. public class ApiResponseBackup {
  12. public static void main(String[] args) {
  13. Scanner scanner = new Scanner(System.in);
  14. System.out.println("API Response Backup Tool");
  15. System.out.println("--------------------------");
  16. String apiResponseFilePath = getApiResponseFilePath(scanner);
  17. String backupDirectory = getBackupDirectory(scanner);
  18. if (apiResponseFilePath == null || backupDirectory == null) {
  19. System.exit(1);
  20. }
  21. backupApiResponses(apiResponseFilePath, backupDirectory);
  22. scanner.close();
  23. }
  24. private static String getApiResponseFilePath(Scanner scanner) {
  25. System.out.print("Enter the path to the API response file: ");
  26. return scanner.nextLine();
  27. }
  28. private static String getBackupDirectory(Scanner scanner) {
  29. System.out.print("Enter the backup directory: ");
  30. return scanner.nextLine();
  31. }
  32. private static void backupApiResponses(String apiResponseFilePath, String backupDirectory) {
  33. try {
  34. // Ensure backup directory exists
  35. if (!new java.io.File(backupDirectory).exists()) {
  36. new java.io.File(backupDirectory).mkdirs();
  37. }
  38. // Extract filename from path
  39. String filename = new java.io.File(apiResponseFilePath).getName();
  40. String fileNameWithoutExtension = filename.substring(0, filename.lastIndexOf('.'));
  41. // Create backup filename with timestamp
  42. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
  43. String timestamp = LocalDateTime.now().format(formatter);
  44. String backupFilename = fileNameWithoutExtension + "_" + timestamp + "." + filename.substring(filename.lastIndexOf('.')) ;
  45. String backupFilePath = backupDirectory + "/" + backupFilename;
  46. // Copy the API response to the backup file
  47. try (BufferedWriter writer = new BufferedWriter(new FileWriter(backupFilePath))) {
  48. try (BufferedReader reader = new BufferedReader(new FileReader(apiResponseFilePath))) {
  49. String line;
  50. while ((line = reader.readLine()) != null) {
  51. writer.write(line);
  52. writer.newLine();
  53. }
  54. }
  55. } catch (IOException e) {
  56. System.err.println("Error during backup: " + e.getMessage());
  57. return;
  58. }
  59. System.out.println("Backup created successfully at: " + backupFilePath);
  60. } catch (Exception e) {
  61. System.err.println("An error occurred: " + e.getMessage());
  62. }
  63. }
  64. }

Add your comment