1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. import java.io.ObjectOutputStream;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class CLIArgumentSerializer {
  7. public static void serializeArguments(Map<String, String> arguments, String filePath) throws IOException {
  8. // Create an ObjectOutputStream to write the arguments to a file.
  9. try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
  10. // Write the arguments map to the output stream.
  11. oos.writeObject(arguments);
  12. }
  13. }
  14. public static Map<String, String> deserializeArguments(String filePath) throws IOException, ClassNotFoundException {
  15. // Read the arguments map from the file.
  16. Map<String, String> arguments = new HashMap<>();
  17. try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
  18. // Read the arguments map from the input stream.
  19. arguments = (Map<String, String>) ois.readObject();
  20. }
  21. return arguments;
  22. }
  23. public static void main(String[] args) {
  24. // Example Usage:
  25. Map<String, String> arguments = new HashMap<>();
  26. arguments.put("name", "John Doe");
  27. arguments.put("age", "30");
  28. arguments.put("city", "New York");
  29. String filePath = "cli_arguments.ser";
  30. // Serialize the arguments to a file.
  31. try {
  32. serializeArguments(arguments, filePath);
  33. System.out.println("Arguments serialized to " + filePath);
  34. // Deserialize the arguments from the file.
  35. Map<String, String> deserializedArguments = deserializeArguments(filePath);
  36. System.out.println("Arguments deserialized: " + deserializedArguments);
  37. } catch (IOException | ClassNotFoundException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }

Add your comment