Autocrab

ObjectSerializer

Jan 29th, 2015
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. public class ObjectSerializer {
  2.  
  3.     public static String serialize(Serializable obj) throws IOException {
  4.         if (obj == null) return "";
  5.         ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
  6.         ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
  7.         objStream.writeObject(obj);
  8.         objStream.close();
  9.         return encodeBytes(serialObj.toByteArray());
  10.     }
  11.  
  12.     public static Object deserialize(CharSequence str) throws IOException, ClassNotFoundException {
  13.         if (str == null || str.length() == 0) return null;
  14.         ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
  15.         ObjectInput objStream = new ObjectInputStream(serialObj);
  16.         return objStream.readObject();
  17.     }
  18.  
  19.     public static String encodeBytes(byte[] bytes) {
  20.         StringBuilder strBuf = new StringBuilder();
  21.  
  22.         for (byte aByte : bytes) {
  23.             strBuf.append((char) (((aByte >> 4) & 0xF) + ((int) 'a')));
  24.             strBuf.append((char) (((aByte) & 0xF) + ((int) 'a')));
  25.         }
  26.  
  27.         return strBuf.toString();
  28.     }
  29.  
  30.     public static byte[] decodeBytes(CharSequence str) {
  31.         byte[] bytes = new byte[str.length() / 2];
  32.         for (int i = 0; i < str.length(); i+=2) {
  33.             char c = str.charAt(i);
  34.             bytes[i/2] = (byte) ((c - 'a') << 4);
  35.             c = str.charAt(i+1);
  36.             bytes[i/2] += (c - 'a');
  37.         }
  38.         return bytes;
  39.     }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment