JackOUT

Untitled

Jan 5th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. /**
  2.      * Read the object from Base64 string.
  3.      */
  4.     public static Object fromString(final String string) throws IOException, ClassNotFoundException {
  5.         final byte[] data = Base64.getDecoder().decode(string);
  6.         final ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));
  7.         final Object object = objectInputStream.readObject();
  8.  
  9.         objectInputStream.close();
  10.         return object;
  11.     }
  12.  
  13.     /**
  14.      * Write the object to a Base64 string.
  15.      */
  16.     public static String toString(final Serializable object) throws IOException {
  17.         final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  18.         final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
  19.  
  20.         objectOutputStream.writeObject(object); // must be serializable
  21.         objectOutputStream.close();
  22.  
  23.         return Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
  24.     }
  25.  
  26.     /**
  27.      * Write the object to a byte array.
  28.      */
  29.     public static byte[] serialize(final Object obj) throws IOException {
  30.         final ByteArrayOutputStream out = new ByteArrayOutputStream();
  31.         final ObjectOutputStream os = new ObjectOutputStream(out);
  32.  
  33.         os.writeObject(obj);
  34.         return out.toByteArray();
  35.     }
  36.  
  37.     /**
  38.      * Read the object from a byte array.
  39.      */
  40.     public static Object deserialize(final byte[] data) throws IOException, ClassNotFoundException {
  41.         final ByteArrayInputStream in = new ByteArrayInputStream(data);
  42.         final ObjectInputStream is = new ObjectInputStream(in);
  43.  
  44.         return is.readObject();
  45.     }
  46.  
  47.     public static Map<String, Object> convertWithStream(final String mapAsString) {
  48.         final Map<String, Object> map = Arrays.stream(mapAsString.split(","))
  49.                 .map(entry -> entry.split("="))
  50.                 .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
  51.         return map;
  52.     }
  53.  
  54.     public static Map<String, String> convertWithGuava(final String mapAsString) {
  55.         return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
  56.     }
Add Comment
Please, Sign In to add comment