import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TaskQueueRestorer {
private static final String DEFAULT_FILE_EXTENSION = ".taskqueue";
/**
* Restores task queue data from a file.
*
* @param queueName The name of the task queue.
* @param filePath The path to the file containing the queue data.
* @return A list of tasks in the queue, or null if an error occurred.
*/
public static List<String> restoreQueue(String queueName, String filePath) {
List<String> tasks = new ArrayList<>();
try (FileInputStream fis = new FileInputStream(filePath);
ObjectInputStream ois = new ObjectInputStream(fis)) {
// Read the queue data from the file.
Object queueObject = ois.readObject();
if (queueObject instanceof List) {
tasks = (List<String>) queueObject; // Cast to List<String>
} else {
System.err.println("Error: Invalid queue data format in file: " + filePath);
return null; // Indicate an error
}
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error restoring queue from file: " + filePath + ". " + e.getMessage());
return null; // Indicate an error
}
return tasks;
}
/**
* Saves task queue data to a file for backup.
*
* @param queueName The name of the task queue.
* @param tasks The list of tasks to save.
* @param filePath The path to the file to save the queue data to.
*/
public static void saveQueue(String queueName, List<String> tasks, String filePath) {
try (FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(tasks);
System.out.println("Queue '" + queueName + "' saved to: " + filePath);
} catch (IOException e) {
System.err.println("Error saving queue to file: " + filePath + ". " + e.getMessage());
}
}
public static void main(String[] args) {
// Example usage
String queueName = "myQueue";
String filePath = "myQueue" + DEFAULT_FILE_EXTENSION;
// Restore the queue
List<String> restoredTasks = restoreQueue(queueName, filePath);
if (restoredTasks != null) {
System.out.println("Restored tasks:");
for (String task : restoredTasks) {
System.out.println(task);
}
} else {
System.out.println("Queue restoration failed.");
}
// Save the queue (for demonstration)
List<String> tasksToSave = new ArrayList<>();
tasksToSave.add("Task 1");
tasksToSave.add("Task 2");
tasksToSave.add("Task 3");
saveQueue(queueName, tasksToSave, filePath);
}
}
Add your comment