|
| 1 | +package com.lenovo.sharedperferences; |
| 2 | + |
| 3 | +import android.util.Log; |
| 4 | + |
| 5 | +import java.io.ByteArrayInputStream; |
| 6 | +import java.io.ByteArrayOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.io.ObjectInputStream; |
| 9 | +import java.io.ObjectOutputStream; |
| 10 | +import java.io.Serializable; |
| 11 | + |
| 12 | + |
| 13 | +public class ObjectSerializer { |
| 14 | + |
| 15 | + |
| 16 | + public static String serialize(Serializable obj) throws IOException { |
| 17 | + if (obj == null) return ""; |
| 18 | + try { |
| 19 | + ByteArrayOutputStream serialObj = new ByteArrayOutputStream(); |
| 20 | + ObjectOutputStream objStream = new ObjectOutputStream(serialObj); |
| 21 | + objStream.writeObject(obj); |
| 22 | + objStream.close(); |
| 23 | + return encodeBytes(serialObj.toByteArray()); |
| 24 | + } catch (Exception e) { |
| 25 | + throw new RuntimeException(e); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public static Object deserialize(String str) throws IOException { |
| 30 | + if (str == null || str.length() == 0) return null; |
| 31 | + try { |
| 32 | + ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str)); |
| 33 | + ObjectInputStream objStream = new ObjectInputStream(serialObj); |
| 34 | + return objStream.readObject(); |
| 35 | + } catch (Exception e) { |
| 36 | + throw new RuntimeException(e); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static String encodeBytes(byte[] bytes) { |
| 41 | + StringBuffer strBuf = new StringBuffer(); |
| 42 | + |
| 43 | + for (int i = 0; i < bytes.length; i++) { |
| 44 | + strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a'))); |
| 45 | + strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a'))); |
| 46 | + } |
| 47 | + |
| 48 | + return strBuf.toString(); |
| 49 | + } |
| 50 | + |
| 51 | + public static byte[] decodeBytes(String str) { |
| 52 | + byte[] bytes = new byte[str.length() / 2]; |
| 53 | + for (int i = 0; i < str.length(); i+=2) { |
| 54 | + char c = str.charAt(i); |
| 55 | + bytes[i/2] = (byte) ((c - 'a') << 4); |
| 56 | + c = str.charAt(i+1); |
| 57 | + bytes[i/2] += (c - 'a'); |
| 58 | + } |
| 59 | + return bytes; |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments