1. import java.io.*;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. public class TaskQueueRestorer {
  7. private static final String DEFAULT_FILE_EXTENSION = ".taskqueue";
  8. /**
  9. * Restores task queue data from a file.
  10. *
  11. * @param queueName The name of the task queue.
  12. * @param filePath The path to the file containing the queue data.
  13. * @return A list of tasks in the queue, or null if an error occurred.
  14. */
  15. public static List<String> restoreQueue(String queueName, String filePath) {
  16. List<String> tasks = new ArrayList<>();
  17. try (FileInputStream fis = new FileInputStream(filePath);
  18. ObjectInputStream ois = new ObjectInputStream(fis)) {
  19. // Read the queue data from the file.
  20. Object queueObject = ois.readObject();
  21. if (queueObject instanceof List) {
  22. tasks = (List<String>) queueObject; // Cast to List<String>
  23. } else {
  24. System.err.println("Error: Invalid queue data format in file: " + filePath);
  25. return null; // Indicate an error
  26. }
  27. } catch (IOException | ClassNotFoundException e) {
  28. System.err.println("Error restoring queue from file: " + filePath + ". " + e.getMessage());
  29. return null; // Indicate an error
  30. }
  31. return tasks;
  32. }
  33. /**
  34. * Saves task queue data to a file for backup.
  35. *
  36. * @param queueName The name of the task queue.
  37. * @param tasks The list of tasks to save.
  38. * @param filePath The path to the file to save the queue data to.
  39. */
  40. public static void saveQueue(String queueName, List<String> tasks, String filePath) {
  41. try (FileOutputStream fos = new FileOutputStream(filePath);
  42. ObjectOutputStream oos = new ObjectOutputStream(fos)) {
  43. oos.writeObject(tasks);
  44. System.out.println("Queue '" + queueName + "' saved to: " + filePath);
  45. } catch (IOException e) {
  46. System.err.println("Error saving queue to file: " + filePath + ". " + e.getMessage());
  47. }
  48. }
  49. public static void main(String[] args) {
  50. // Example usage
  51. String queueName = "myQueue";
  52. String filePath = "myQueue" + DEFAULT_FILE_EXTENSION;
  53. // Restore the queue
  54. List<String> restoredTasks = restoreQueue(queueName, filePath);
  55. if (restoredTasks != null) {
  56. System.out.println("Restored tasks:");
  57. for (String task : restoredTasks) {
  58. System.out.println(task);
  59. }
  60. } else {
  61. System.out.println("Queue restoration failed.");
  62. }
  63. // Save the queue (for demonstration)
  64. List<String> tasksToSave = new ArrayList<>();
  65. tasksToSave.add("Task 1");
  66. tasksToSave.add("Task 2");
  67. tasksToSave.add("Task 3");
  68. saveQueue(queueName, tasksToSave, filePath);
  69. }
  70. }

Add your comment