@weixin
2014-08-11T05:17:35.000000Z
字数 2250
阅读 1244
java
open-source
code
public static void serialize(final Serializable obj, final OutputStream outputStream) {
if (outputStream == null) {
throw new IllegalArgumentException("The OutputStream must not be null");
}
ObjectOutputStream out = null;
try {
// stream closed in the finally
out = new ObjectOutputStream(outputStream);
out.writeObject(obj);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (out != null) {
out.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
public static <T> T deserialize(final InputStream inputStream) {
if (inputStream == null) {
throw new IllegalArgumentException("The InputStream must not be null");
}
ObjectInputStream in = null;
try {
// stream closed in the finally
in = new ObjectInputStream(inputStream);
@SuppressWarnings("unchecked") // may fail with CCE if serialised form is incorrect
final T obj = (T) in.readObject();
return obj;
} catch (final ClassCastException ex) {
throw new SerializationException(ex);
} catch (final ClassNotFoundException ex) {
throw new SerializationException(ex);
} catch (final IOException ex) {
throw new SerializationException(ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (final IOException ex) { // NOPMD
// ignore close exception
}
}
}
public void serializationUtilsDemo() {
System.out.println ("*SerializationUtils**");
Date date = new Date();
byte[] bytes = SerializationUtils.serialize (date);
System.out.println (ArrayUtils.toString (bytes) );
System.out.println (date);
Date reDate = (Date) SerializationUtils.deserialize (bytes);
System.out.println (reDate);
System.out.println (ObjectUtils.equals (date, reDate) );
System.out.println (date == reDate);
FileOutputStream fos = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream (new File ("./serialize_test.txt") );
fis = new FileInputStream (new File ("./serialize_test.txt") );
SerializationUtils.serialize (date, fos);
Date reDate2 = (Date) SerializationUtils.deserialize (fis);
System.out.println (date.equals (reDate2) );
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
the result is :
SerializationUtils*
{-84,-19,0,5,115,114,0,14,106,97,118,97,46,117,116,105,108,46,68,97,116,101,104,106,-127,1,75,89,116,25,3,0,0,120,112,119,8,0,0,1,71,-61,123,-20,-66,120}
Sun Aug 10 22:13:04 PDT 2014
Sun Aug 10 22:13:04 PDT 2014
true
false
true