Last active
September 8, 2020 05:51
-
-
Save thejavalistener/8821259 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package demo; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
import java.util.Date; | |
public class Serialize | |
{ | |
public static byte[] toBytes(Serializable o) | |
{ | |
ByteArrayOutputStream os = null; | |
ObjectOutputStream oos = null; | |
try | |
{ | |
os = new ByteArrayOutputStream(); | |
oos = new ObjectOutputStream(os); | |
oos.writeObject(o); | |
return os.toByteArray(); | |
} | |
catch(Exception ex) | |
{ | |
ex.printStackTrace(); | |
throw new RuntimeException(ex); | |
} | |
finally | |
{ | |
try | |
{ | |
if( oos!=null ) oos.close(); | |
if( os!=null ) os.close(); | |
} | |
catch(Exception ex2) | |
{ | |
ex2.printStackTrace(); | |
throw new RuntimeException(ex2); | |
} | |
} | |
} | |
public static Object toObject(byte[] s) | |
{ | |
ByteArrayInputStream is = null; | |
ObjectInputStream ois = null; | |
try | |
{ | |
is = new ByteArrayInputStream(s); | |
ois = new ObjectInputStream(is); | |
return ois.readObject(); | |
} | |
catch(Exception ex) | |
{ | |
ex.printStackTrace(); | |
throw new RuntimeException(ex); | |
} | |
finally | |
{ | |
try | |
{ | |
if( ois!=null ) ois.close(); | |
if( is!=null ) is.close(); | |
} | |
catch(Exception ex2) | |
{ | |
ex2.printStackTrace(); | |
throw new RuntimeException(ex2); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment